silver
silver

Reputation: 64

How to input a 'onchange' event on several checkbox

I have this checkbox:

<input type="checkbox" name="foo[]" value="111111">
<input type="checkbox" name="foo[]" value="222222">
<input type="checkbox" name="foo[]" value="333333">

And i'm trying to get the value from the selected checkbox

    $("input:checkbox[name^='foo']").each(function(){
        var val = $(this).val();
        alert(val);
    });

But the event isn't called.. Am I doing something wrong?

Sorry for bad english!

Upvotes: 0

Views: 1974

Answers (3)

PeterKA
PeterKA

Reputation: 24638

Something very fundamental many of us for get is DOM ready:

$(function() {
    $(":checkbox[name^='foo']").on('change', function () {
        alert(this.value + ' --- ' + this.checked);
    });
});

JS FIDDLE DEMO

Upvotes: 1

Anoop Joshi P
Anoop Joshi P

Reputation: 25537

USe is(":checked") to check whether the checkbox is checked

$("input:checkbox[name^='foo']").click(function () {
    $("input:checkbox[name^='foo']").each(function () {
        if ($(this).is(":checked")) {
            alert($(this).val());
        }
    });
});

Demo

Upvotes: 1

Venkata Krishna
Venkata Krishna

Reputation: 15112

Don't use each.

Use .on('change') for your event. Also this.value is easier than $(this).val().

http://jsfiddle.net/65u2t/

$("input:checkbox[name^='foo']").on('change', function () {
    var val = this.value;
    alert(val);
});

Upvotes: 1

Related Questions