首页 > 解决方案 > 按顺序将动态创建的文本框值存储在 javascript 数组中

问题描述

我通过单击button使用 AJAX 开发了动态创建的文本框。morning我有三个文本框 ID ,例如noonnight。我只想将这些值存储在一个数组中[morning, noon, night][morning, noon, night]...

我试过了,但它的存储方式是[morning, morning, noon, noon, night, night]. 如上所述,我无法理解如何分离。

请帮我解决我的问题。

$(document).ready(function() {
  $(document).on('click', '#submit', function() {
    var modess = [
      $("input[id='morning[]']").map(function() {
        return $(this).val();
        console.log(morning);
      }).get(),

      $("input[id='noon[]']").map(function() {
        return $(this).val();
        console.log(noon);
      }).get(),

      $("input[id='night[]']").map(function() {
        return $(this).val();
        console.log(night);
      }).get(),
    ]

    alert(modess);

    const medic = [...morning, ...noon, ...night];
    console.log(medic);
    var medical = JSON.stringify(medic);
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="table table-bordered mb-0" id="medical">
  <thead>
    <tr>
      <th>Medicine Name</th>
      <th>Morning</th>
      <th>Noon</th>
      <th>Night</th>
      <th>charge</th>
      <th> <button type="button" name="add" id="add" class="btn btn-success btn-xs"> + </button> </th>
    </tr>
  </thead>
  <tbody id="rows"></tbody>
</table>

标签: javascriptjquery

解决方案


问题是因为您是按输入分组,而不是按表中的行分组。

另请注意,您似乎id在多个元素上使用相同,这是无效的。它们必须是独一无二的。改为对它们使用一个通用类。然后您可以使用map()从这些字段中选择值,如下所示:

let modess = $('#rows tr').map(function() {
  let $tr = $(this);
  return [
    $tr.find('.morning').val(),
    $tr.find('.noon').val(),
    $tr.find('.night').val(),
  ];
});

推荐阅读