Friday, October 29, 2010

Retrieving checkboxes values using JQuery...

I have an html like this in my page
    ...
    <div id="container1">
        <input type="checkbox" value="1" /> a
        <input type="checkbox" value="2" /> b
        <input type="checkbox" value="3" /> c
        <input type="checkbox" value="4" /> d
        <input type="checkbox" value="5" /> e
        <input type="checkbox" value="6" /> f
    </div>

    <div id="container2">
        <input type="checkbox" value="11" /> a1
        <input type="checkbox" value="12" /> b1
        <input type="checkbox" value="13" /> c1
        <input type="checkbox" value="14" /> d1
        <input type="checkbox" value="15" /> e1
        <input type="checkbox" value="16" /> f1
    </div>
    <input id="mybutton" type="button" value="click me" />
    ...

Demo

container1
a b c d e f

container2
a1 b1 c1 d1 e1 f1

result


Now what I want is, whenever I click the button I want to retrieve all the values from the checked checkboxes. This is pretty easy in JQuery. Here's how my JS will look like
    ...
    $("#mybutton").click( function() {
        var myarray = [];
        
        $('input:checkbox:checked').each( function() {
            myarray.push($(this).val());
        });
        
        alert(myarray.join(', '));
    } );
    ...
What if I want it only from the first <div>? I just need to pass context to the selector
    ...
    $("#mybutton").click( function() {
        var myarray = [];
        
        // passing container1 as context to selector
        $('input:checkbox:checked', '#container1').each( function() {
            myarray.push($(this).val());
        });
        
        alert(myarray.join(', '));
    } );
    ...
JQuery makes my life a lot easier :).

No comments:

Post a Comment