7

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/

1

3 Answers 3

12

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

8

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.

3

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.