user3723240
user3723240

Reputation: 393

Jquery create arrays inside an array

I have two sets of checkboxes like so:

<ul id="searchFilter">
    <li class="">
        <input type="checkbox" name="location[]" class="cb_location" value="1">Toronto</li>
    <li class="">
        <input type="checkbox" name="location[]" class="cb_location" value="3">New York</li>
    <li class="">
        <input type="checkbox" name="location[]" class="cb_location" value="6">London</li>
    <li class="">
        <input type="checkbox" name="location[]" class="cb_location" value="5">Paris</li>
    <li class="">
        <input type="checkbox" name="location[]" class="cb_location" value="4">Berlin</li>
</ul>

        <ul id="searchFilter">
                    <li><input type="checkbox" name="price[]" class="cb_price" value="2"> $200,000 to $299,999</li>
                    <li><input type="checkbox" name="price[]" class="cb_price" value="3"> $300,000 to $399,999</li>
                    <li><input type="checkbox" name="price[]" class="cb_price" value="4"> $400,000 to $499,999</li>
                    <li><input type="checkbox" name="price[]" class="cb_price" value="5"> $500,000+</li>
                </ul>

and I have this jquery code that takes the value of what is selected and puts into an opts array:

$(':checkbox').change(function() {
   var opts = $(":checkbox:checked").map(function() {
        return $(this).val();
    }).get(); 
    console.log(opts);
});

but this will return the values of checked checkboxes values, regardless of which set of checkboxes they are in, my question is how would I keep these separate, but in the opts array, I am looking for these results:

[location[1, 2, 3], price[1, 2, 3]]

here is a fiddle: http://jsfiddle.net/6zz5f/1/

Upvotes: -1

Views: 617

Answers (2)

Blazemonger
Blazemonger

Reputation: 93003

To create a complex object like that, you'll need to build it explicitly:

$(':checkbox').change(function () {
    var opts = {};
    $(":checkbox:checked").each(function () {
        var name = this.name;
        if (!opts[name]) opts[name] = [];
        opts[name].push(this.value);
    });
    console.log(opts);
});

http://jsfiddle.net/mblase75/Ttv3y/

The result will be something like:

{ location[]: [1,2,3], price[]: [4,5,6] }

You can remove the [] from the checkbox names inside the loop if you need to:

var name = this.name.substring(0,this.name.length-2);

Upvotes: 0

Alnitak
Alnitak

Reputation: 340055

If the set of checkboxes is small enough, and known in advance, just evaluate each of them separately:

function getValues(selector) {
    var $checked = $(':checkbox:checked');
    if (selector) {
        $checked = $checked.filter(selector);
    }

    return $checked.map(function() {
        return this.value;
    }).get();
};

$(':checked').on('change', function() {
    console.log({
        location: getValues('.cb_location'),
        price: getValues('.cb_price');
    });
});

Upvotes: -1

Related Questions