How do you check if a checkbox is checked with jQuery? No, it?s not a tongue-twister! Let?s say you?ve got this input:
<input type=”checkbox” name=”agree” checked>I agree to stuff
It?ll be checked by default because of the checked attribute. jQuery allows you to check a DOM element?s attribute through the .attr() method e.g.:
$(‘input[type=checkbox]’).attr(‘checked’);
So we can just check the checked attribute and that will tell us?
Not exactly. The checked attribute simply tells you whether the checkbox is checked or not by default when the page is rendered. It does not tell you the current state of the checkbox.
$(‘input[type=checkbox]’).attr(‘checked’);// Returns ?true? if present on the element, returns undefined if not present
To check the current state of the checkbox you must instead use the checked property. It is dynamically updated as the user checks/unchecks. jQuery allow you to check a property with the .prop() method like so:
$(‘input[type=checkbox]’).prop(‘checked’);// Returns true if checked, false if unchecked.
We go into much more detail and show a live example in the video below.
JS Dojo: Javascript Tutorials With Real-Time Help
Raise your skill to professional level in a live, interactive coding environment with an industry expert looking over your shoulder.
To learn more about JS Dojo and to join our private beta program, visit us here: https://getjsdojo.com
JS Dojo ? Javascript Tutorials With Real-Time Help