Get an associative array from the input using jQuery

advertisements

I would like to have an associative array from a form with multiple text input with jQuery (or directly in JS). From that :

<form>
<input type="text" name="name[13]" value="test 1" />
<input type="text" name="name[14]" value="test 2" />
<input type="text" name="new_name[]" value="test 3" />
</form>

I would like to get that :

name : Array {
    13 => "test 1",
    14 => "test 2"
}
new_name : Array {
    1 => "test 3"
}

I try with the serialize function of jQuery and it works only for array like the new_name one.

Thanks for your help ! Kevin


You can try something like:

var output = [];

$('input[type="text"]').each(function() {

  var s = $(this).attr('name').match(/(.*)[(.*)]/);

  var found = false;
  for(x in output) {
    if(x == s[0]) {
      output[x].push({s[1]: $(this).val()});
      found = true;
    }
  }

  if(!found) {
    output[s[0]] = [{s[1]: $(this).val()}];
  }

});