The checkbox is always on
Why does this code always warn "on"? Whether checked or not, it always prints.
click:
<input type="checkbox" onclick="alert(this.value)" />
http://jsfiddle.net/5yn78jhz/
+3
Maigret
source
to share
3 answers
Your checkbox is irrelevant, so JavaScript uses the default. If you want something else you need to use the value attribute value="some value"
. Also, the code does not check if the checkbox was checked or not, so it always gives you the value of the checkbox whether it is checked or not.
for example
<input type="checkbox" onclick="if(this.checked) { alert(this.value); }" />
Only anything will be displayed if the checkbox is checked.
+5
Robbert
source
to share
Use "this.checked" instead of "value" to get true or false for checked or unchecked.
+5
ynnus
source
to share
This is the onclick action. You can use js function to check if true / false is the following:
Html
<input type="checkbox" onclick="check(this)" />
Js
function check(obj){
if(obj.checked){
alert(obj.value);
}
}
violin
+3
Alex char
source
to share