最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Checkbox always On - Stack Overflow

programmeradmin2浏览0评论

Why this code always alert "on"? No matter if it's checked or unchecked, it always print on.

click:
<input type="checkbox" onclick="alert(this.value)" />

/

Why this code always alert "on"? No matter if it's checked or unchecked, it always print on.

click:
<input type="checkbox" onclick="alert(this.value)" />

http://jsfiddle.net/5yn78jhz/

Share Improve this question edited Sep 17, 2014 at 18:26 Savrige asked Sep 17, 2014 at 18:04 SavrigeSavrige 3,7553 gold badges36 silver badges40 bronze badges 1
  • 1 See this updated version: jsfiddle.net/5yn78jhz/2 – Kelsadita Commented Sep 17, 2014 at 18:08
Add a comment  | 

3 Answers 3

Reset to default 12

Use "this.checked" instead of "value" to get true or false for checked or unchecked.

Your checkbox doesn't have a value, so JavaScript uses the default value. If you want something else, you'll need to use the value attribute value="some value". Also, the code isn't checking to see if the checkbox has been checked or not, so it will always give you the value of the checkbox, whether it's checked or not.

For example

<input type="checkbox" onclick="if(this.checked) { alert(this.value); }" />

Will only display something if the checkbox is checked.

This is the way onclick action works. You can use a js function to check if is true/false like this:

html

<input type="checkbox" onclick="check(this)" />

js

function check(obj){
    if(obj.checked){
        alert(obj.value);
    }
}

fiddle

发布评论

评论列表(0)

  1. 暂无评论