简体   繁体   中英

Get an associative array from input using jQuery

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()}];
  }

});

Here is how I would do it, (I would avoid using jQuery in this particular case)

window.onload=function(){//$(document).ready(...) if you already using jQuery
    var str,str2,arr1=[],arr2=[],inputs=document.getElementsByTagName("input");
    for(var i=0,len=inputs.length;i<len;i++){
        str=inputs[i].name;
        if(inputs[i].type=='text'&&str.charAt(str.length-1)=="]"){
            if(str.substr(0,5)=="name["){
                str2=parseInt(str.split("name[")[1].split("]")[0]);
                if(str2!=NaN){
                    arr1[str2]=inputs[i].value;
                    continue;//we move to the next i
                }//else
            }
            if(str.substr(0,9)=="new_name["){
                str2=parseInt(str.split("new_name[")[1].split("]")[0]);
                if(str2!=NaN){
                    arr2[str2]=inputs[i].value;
                }//else
            }
        }
    }
    alert(arr1[13]);//test 1
}

Here is the jsFiddle demo

Note: When the index is not valid, it won't add it to the arrays, you can easily modify the //else to do something else

What output do you get (in Firebug or Chrome console) if you add the code below and submit the form:

$('form').submit(function() {
  console.log($(this).serializeArray());
  return false;
});

EDIT: this was for the purpose of trying to find out what the OP's issue was in more detail..

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM