Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

onchange event on checkbox always shows this.value = on

An input of type checkbox when fires its onchange event the this.value is always set to on even when the checkbox is ticked off in which case I'd expect it to be off

Is this the intended behavior?

<input type="checkbox" onchange="alert(this.value)">
like image 975
laggingreflex Avatar asked Apr 29 '15 01:04

laggingreflex


People also ask

Does Onchange work for checkbox?

The onchange event occurs when the value of an element has been changed. For radiobuttons and checkboxes, the onchange event occurs when the checked state has been changed.

How do I keep the default value in a checkbox?

If you wanted to submit a default value for the checkbox when it is unchecked, you could include an <input type="hidden"> inside the form with the same name and value , generated by JavaScript perhaps.

What is the value of checkbox when checked?

It has a boolean value which returns true if the checkbox is checked by default, otherwise returns false.


1 Answers

short answer: do not use value to check checked status on checkboxes, use checked instead

<input type="checkbox" onchange="alert(this.checked)">

and in case that you wonder why is this always-"on" value, there's a specification for that in HTML5 specification:

default/on

On getting, if the element has a value attribute, it must return that attribute's value; otherwise, it must return the string "on". On setting, it must set the element's value attribute to the new value.

http://www.w3.org/TR/html5/forms.html#dom-input-value-default-on

like image 52
Santiago Hernández Avatar answered Nov 15 '22 00:11

Santiago Hernández