views:

99

answers:

3

I have several checkboxes and a fake submit button to make an AJAX request:

<form>
    <input type="checkbox" value="1"/>
    <input type="checkbox" value="2" checked="checked"/>
    <input type="checkbox" value="3"/>
    <input type="checkbox" value="4" checked="checked"/>
    <input type="button" onclick="return mmSubmit();"/>
</form>

Within the mmSubmit() method, I would like to retrieve an array of values that have been selected. Here is what I am currently doing.

mmSubmit = function() {
    var ids = [];
    $('input[type=checkbox]:checked');.each(function(index) {
        ids.push($(this).attr('value'));
    });
    // ids now equals [ 2 , 4 ] based upon the checkbox values in the HTML above
    return false;
};

I'm wondering if there is a shorthand method in jQuery used to retrieve the values into an array, or if what I have is already optimal.

A: 

Well you can use .val() instead of .attr('value').

$.serializeArray() may also do what you want (http://docs.jquery.com/Ajax/serializeArray).

Frank Schwieterman
I think the map() function is what I am looking for based upon Quintin Robinson's response, but the val() and serializeArray() methods are definitely good to know about, thanks! :)
Matt Huggins
+2  A: 

I think this can be accomplished with map. Try the following..

mmSubmit = function() {
    var ids = $('input[type=checkbox]:checked').map(function(){
       return $(this).val();
    }).get();
    // ids now equals [ 2 , 4 ] based upon the checkbox values in the HTML above
    return false;
};

Take a look at: jQuery Traversing/Map

Quintin Robinson
A: 

It's needs some optimization, buts generally it is right way. My variant:

mmSubmit = function () {
    var ids = [];
    $('input[type=checkbox]').each(function () {
        if (this.checked) {
            ids[ids.length] = this.value;
        }
    });
    return ids;
};

It's little faster.

Anatoliy