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);
});

      

http://jsfiddle.net/pCmXJ/

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


Or that:



$(this).attr("checked")

      

+2


source


It should be $(this).is(':checked')

+1


source


You need to use the selector :checked

notchecked

status += $(this).val() + ': ' + $(this).is(':checked') + ".\n";

      

+1


source


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







All Articles