Tuesday 4 April 2017

forms - What's the proper value for a checked attribute of an HTML checkbox?

I think this may help:



First read all the specs from Microsoft and W3.org.
You'd see that the setting the actual element of a checkbox needs to be done on the ELEMENT PROPERTY, not the UI or attribute.
$('mycheckbox')[0].checked

Secondly, you need to be aware that the checked attribute RETURNS a string "true", "false"
Why is this important? Because you need to use the correct Type. A string, not a boolean. This also important when parsing your checkbox.
$('mycheckbox')[0].checked = "true"

if($('mycheckbox')[0].checked === "true"){
//do something
}




You also need to realize that the "checked" ATTRIBUTE is for setting the value of the checkbox initially. This doesn't do much once the element is rendered to the DOM. Picture this working when the webpage loads and is initially parsed.
I'll go with IE's preference on this one:



Lastly, the main aspect of confusion for a checkbox is that the checkbox UI element is not the same as the element's property value. They do not correlate directly.
If you work in .net, you'll discover that the user "checking" a checkbox never reflects the actual bool value passed to the controller.
To set the UI, I use both $('mycheckbox').val(true); and $('mycheckbox').attr('checked', 'checked');





In short, for a checked checkbox you need:
Initial DOM:
Element Property: $('mycheckbox')[0].checked = "true";
UI: $('mycheckbox').val(true); and $('mycheckbox').attr('checked', 'checked');

No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...