遍历表单字段并更新数组中的值

时间:2019-03-08 20:47:31

标签: jquery arrays forms loops

我有一个看起来像的

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

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

请协助。

2 个答案:

答案 0 :(得分:0)

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>

遍历数组而不是输入。

答案 1 :(得分:0)

无需遍历输入。这是您要遍历的数组,并使用当前索引访问输入以填充其值:

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.