简体   繁体   English

如何获取与数组(jQuery)具有相同名称标签的所有输入字段

[英]How to get all input-fields with same name-tag as array (jQuery)

Is it possible to get all input-fields with the same name-tag as array and use the string in square bracket as key?是否可以获取与数组具有相同名称标签的所有输入字段并使用方括号中的字符串作为键? Example:例子:

<input type="hidden" name="hidden[idPub]" disabled="disabled">
<input type="hidden" name="hidden[idPri]" disabled="disabled">  
<textarea name="hidden[description]" style="height:75px;length:auto;display:block;" class="form-control" >'</textarea>

The result should be like that:结果应该是这样的:

hidden => 
    "idPub" => 123,
    "idPri" => 321,
    "description" => 'test'

My actual solution:我的实际解决方案:

var formData = [];
        $("input[name^='hidden[']").each(function()
        {
            formData[$(this).attr('name').replace('hidden[','').replace(']', '')] = $(this).val();
        });

Thanks in advance.提前致谢。

const formData = {};

const elements = Array.from(document.querySelectorAll("input[type=hidden]"));

elements.forEach(el => {
    const key = el.getAttribute('name');
    var matches = key.match(/\[(.*?)\]/);

  if (matches) {
    var val = matches[1];
    formData[val] = el.value;
  }
});

console.log(formData);

Because you're using named keys, formData should be an object , not an array.因为您使用的是命名键, formData应该是一个object ,而不是一个数组。

var formData = {};
//             ^^

Additionally, your selector is only targeting <input> elements;此外,您的选择器仅针对<input>元素; you'll want to add a selector for <textarea> as well.您还需要为<textarea>添加一个选择器。

$("input[name^='hidden['],textarea[name^='hidden[']")
//                       ^^^^^^^^^^^^^^^^^^^^^^^^^^

 var formData = {}; $("input[name^='hidden['],textarea[name^='hidden[']").each(function() { formData[$(this).attr('name').replace('hidden[', '').replace(']', '')] = $(this).val(); }); console.log(formData);
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <input type="hidden" name="hidden[idPub]" value="123"> <input type="hidden" name="hidden[idPri]" value="321"> <textarea name="hidden[description]">test</textarea>

you can do this using regex as well.您也可以使用正则表达式执行此操作。

var hidden = {};
$('input,textarea').filter(function(){
  return this.name.match(/(hidden)\[(.*?)\]/g);
}).each(function() {
  hidden[$(this).attr('name').replace('hidden[', '').replace(']', '')] = $(this).val();
});

console.log(hidden);

Check it out here: How to get all input-fields with same name-tag as array (jQuery)在这里查看:如何获取与数组(jQuery)具有相同名称标签的所有输入字段

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

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