Murphy1976
Murphy1976

Reputation: 1475

jQuery Checkboxes to Populate Mutlidimensional Array

I have a list of checkboxes:

<input type="checkbox" name="a" value="cb1" value2="value01" class="sort" />
<input type="checkbox" name="a" value="cb2" value2="value02" class="sort" />
<input type="checkbox" name="a" value="cb3" value2="value03" class="sort" />
<input type="checkbox" name="a" value="cb4" value2="value04" class="sort" />

And what I would like to do, is when I toggle these on or off, they populate an Multidimensional array (Arr_Sort[0][1]), just two levels ONLY.

Here's my script code that works fine to populate a single dimensional array, I just don't know how to modify it to populate a multidimensional array.

$(document).ready(function(){

    $(".sort").change(function()
    {
        var arr_sort = new Array();

        $(".sort").each(function()
        {
            if( $(this).is(':checked') )
            {
                arr_sort.push($(this).val());
            }
        });
        alert( arr_sort );
    });
});

Upvotes: 0

Views: 199

Answers (2)

Raja Sekar
Raja Sekar

Reputation: 2130

 $(document).ready(function(){
var arr_sort = [];
    $(".sort").change(function(){
        $(this).each(function(key,val){
            if( $(this).is(':checked') ){
                arr_sort[ $(this).index() + 1] = $(this).val();
            }else{
                arr_sort.remove($(this).val());
            }
        });
        console.log( arr_sort );
    });
});

Array.prototype.remove = function() {
    var what, a = arguments, L = a.length, ax;
    while (L && this.length) {
        what = a[--L];
        while ((ax = this.indexOf(what)) !== -1) {
            this.splice(ax, 1);
        }
    }
    return this;
};
  1. Declare ARRAY as [] to improve performance.
  2. declare array out of change function.
  3. Handle negative scenario also, If the value is removed, it should be removed from the array.

Upvotes: 0

MSTannu
MSTannu

Reputation: 1033

try replacing arr_sort.push( $( this ).val() );

with

arr_sort.push( new Array( $( this ).val(), $( this ).attr( 'value2' ) ) );

Upvotes: 1

Related Questions