【问题标题】:Loop thru form fields and update values from array循环表单字段并更新数组中的值
【发布时间】:2019-07-30 22:21:44
【问题描述】:

我有一个看起来像的

    <div class="book-form">
    <input type="text" id="book_qty" name="book_qty[0]" value="" >
    <input type="text" id="book_unit" name="book_unit[0]" value="" >
    <input type="text" id="book_name" name="book_name[0]" value="" >
    <input type="text" id="book_notes" name="book_notes[0]" value="" >

    <input type="text" id="book_qty" name="book_qty[1]" value="" >
    <input type="text" id="book_unit" name="book_unit[1]" value="" >
    <input type="text" id="book_name" name="book_name[1]" value="" >
    <input type="text" id="book_notes" name="book_notes[1]" value="" >
    </div>

然后我有一个数组,其中包含与上述表单相同的映射值

    0: Array(4)
    0: "1 "
    1: "boxes "
    2: "Math"
    3: "in Stock"
    length: 4

    1: Array(4)
    0: "2 "
    1: "boxes "
    2: "science "
    3: " "
    length: 4

我正在尝试遍历数组并分别更新表单字段。

这是我尝试过的代码

  var all_inputs = $(".autofill input[type=text]");
  $(all_inputs).each(function() {
  $.each(myTableArray, function (n, elem) {
  console.log(elem);
  all_inputs.val(elem);
  });
  });

但这会用相同的最后一个值填充表单。

请帮忙。

【问题讨论】:

  • ID 应该是唯一的,你不应该有多个 id="book_qty"

标签: jquery arrays forms loops


【解决方案1】:

无需循环输入。它是您要循环并使用当前索引访问输入以填充其值的数组:

var myTableArray = [
  ["1 ", "boxes ", "Math", "in Stock"],
  ["2 ", "boxes ", "science ", " "]
];

var all_inputs = $("input[type=text]");
var cnt = 0;

$.each(myTableArray, function(n, e) {
  $.each(e, function(n, elem) {
    console.log(elem);
    $(all_inputs.get(cnt)).val(elem);
    cnt++;
  });
});

Here is the working fiddle.

【讨论】:

    【解决方案2】:

    const array = [
      ["1 ", "boxes ", "Math", "in Stock"],
      ["2 ", "boxes ", "science ", " "]
    ];
    array.forEach(([qty, unit, name, notes], i) => {
      $(`input[name="book_qty[${i}]"]`).val(qty.trim());
      $(`input[name="book_unit[${i}]"]`).val(unit.trim());
      $(`input[name="book_name[${i}]"]`).val(name.trim());
      $(`input[name="book_notes[${i}]"]`).val(notes.trim());
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div class="book-form">
      <input type="text" id="book_qty" name="book_qty[0]" value="">
      <input type="text" id="book_unit" name="book_unit[0]" value="">
      <input type="text" id="book_name" name="book_name[0]" value="">
      <input type="text" id="book_notes" name="book_notes[0]" value="">
    
      <input type="text" id="book_qty" name="book_qty[1]" value="">
      <input type="text" id="book_unit" name="book_unit[1]" value="">
      <input type="text" id="book_name" name="book_name[1]" value="">
      <input type="text" id="book_notes" name="book_notes[1]" value="">
    </div>

    循环遍历数组而不是输入。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-05-12
      • 1970-01-01
      • 2017-06-22
      • 2015-12-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多