【问题标题】:jQuery: Get value from input array with predefined array keyjQuery:使用预定义的数组键从输入数组中获取值
【发布时间】:2022-01-15 06:57:12
【问题描述】:

我有一个带有预定义数组键的 html 输入数组(进一步操作需要预定义键),如下所示:

<input type="hidden" name="tests[5]" value="b">
<input type="hidden" name="tests[8]" value="a">

我尝试使用这样的 jQuery 方法获取值:

var testsValues = $('input[name="tests[]"]').map(function () {
                return this.value; // $(this).val()
           }).get();

console.log(testsValues);

它总是给出一个空的结果,但是如果我删除预定义的键它不会给出一个空的结果

<input type="hidden" name="tests[]" value="b">
<input type="hidden" name="tests[]" value="a">

使用预定义键检索输入数组值的正确方法是什么?

【问题讨论】:

标签: html jquery


【解决方案1】:

您可以使用更好的选择器,例如 $('input[name^="tests"]') 来获取以 tests 开头的元素名称,然后将它们循环起来。

编辑:要获取密钥,您可以使用输入的分隔符“[”拆分名称以获取第二个元素[1],然后替换最后一个元素使其干净“]”。

https://api.jquery.com/each/

https://api.jquery.com/category/selectors/

$('input[name^="tests"]').each(function() {
  let inputName = $(this).attr("name");
  let inputKey = inputName.split('[')[1].replace(']', '');
  let inputVal = $(this).val();
  console.log("Name : " + inputName + " - Key : " + inputKey + " - " + " Value : " + inputVal);
  
  if (inputKey == 5) {
    // do something
    console.log("Key is egal to 5 - Value : " + inputVal);
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="hidden" name="tests[5]" value="b">
<input type="hidden" name="tests[8]" value="a">

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-04-09
    • 1970-01-01
    • 2020-07-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多