Jquery: get sent values ​​for name in array format

on submit, I need to collect values ​​for a number of checkbox fields with a common name in array format. I tried to do something like:

$('form').submit(function(e){   
  $(':input:checkbox[name=fields[]]', this).each(function(){
    console.log($(this).attr('name'));
    console.log($(this).val);
  });
});

but "[name = fields []]" does not limit how I think. what I ultimately need to do is determine how many flags were checked in this array of fields. I just send to the console log while I figure out the conditions.

+3
source share
1 answer

Edited by:

$('form').submit(function(e){   
    var fields = new Array();
    $(':input:checkbox[name*=fields]', this).each(function() {
        index_a = $(this).attr('name');
        if (fields[index_a] == undefined) fields[index_a] = 0;
        if ($(this).is(':checked')) fields[index_a] += 1;
    });
    return false;
});

http://jsfiddle.net/daybreaker/7UFs6/3

This will return an array fieldswith keys for each fields[whatever]and a value equal to the number of check marks in each field[whatever].

jsfiddle fields[opt1] fields[opt2], , , , . , , opt1 .

+4

All Articles