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
3 Answers
Reset to default 12Use "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