Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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/

You know tell me why the two checkbox always return false? Thanks.

like image 836
Caio Tarifa Avatar asked Apr 26 '26 10:04

Caio Tarifa


2 Answers

Probably because you want the :checked selector:

$(this).is(":checked") // <-- Note the colon (:) before "checked"

Example: http://jsfiddle.net/nht6w/

like image 111
Andrew Whitaker Avatar answered Apr 30 '26 08:04

Andrew Whitaker


Or this :

$(this).attr("checked")
like image 29
Pheonix Avatar answered Apr 30 '26 07:04

Pheonix