简体   繁体   English

使用jQuery从输入获取关联数组

[英]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). 我想使用jQuery(或直接在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. 我尝试使用jQuery的序列化功能,它仅适用于像new_name这样的数组。

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) 这是我的方法(在这种特殊情况下,我将避免使用jQuery)

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 这是jsFiddle演示

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 注意:当索引无效时,它不会将其添加到数组中,您可以轻松修改//else以执行其他操作

What output do you get (in Firebug or Chrome console) if you add the code below and submit the form: 如果您添加以下代码并提交表单,您将在Firebug或Chrome控制台中获得什么输出:

$('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.. 编辑:这是为了尝试更详细地了解OP的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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