Input checkbox always returns false
I have the following code:
Html
<div id='foo'>
<input type='checkbox' value='english' name='bar[english]' />
<input type='checkbox' value='spanish' name='bar[spanish]' />
<button type='button' class='button'>Me!</button>
</div>
JavaScript (jQuery)
$('.button').click(function() {
status = '';
$('#foo input[name*="bar"]').each(function() {
status += $(this).val() + ': ' + $(this).is('checked') + ".\n";
});
alert(status);
});
Do you know tell me why the two checkboxes always return false? Thank.
+3
source to share
5 answers
Perhaps because you want a :checked
selector :
$(this).is(":checked") // <-- Note the colon (:) before "checked"
Example: http://jsfiddle.net/nht6w/
+8
source to share
Since you are checking if an input
element is an element checked
, which of course is not as an element input
(and there are no elements checked
). Use a :checked
pseudo selector :
$(this).is(':checked')
+1
source to share