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


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


source


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



+5


source


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


source







All Articles