简体   繁体   English

将动态创建的文本框值按顺序存储在 javascript 数组中

[英]Store dynamically created text box values in an javascript array in an order

I have developed dynamically created text boxes by clicking a button using AJAX.我通过使用 AJAX 单击button开发了动态创建的文本框。 I have three text box IDs such as morning , noon and night .我有三个文本框 ID,例如morningnoonnight I just want to store these values in an array like [morning, noon, night][morning, noon, night]...我只想将这些值存储在一个数组中,例如[morning, noon, night][morning, noon, night]...

I have tried, but it stored like [morning, morning, noon, noon, night, night] .我试过,但它存储为[morning, morning, noon, noon, night, night] I can't understand how to separate as I mentioned above.正如我上面提到的,我无法理解如何分离。

Please help me to solve my problem.请帮我解决我的问题。

 $(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>

The issue is because you're grouping by input, not by row in the table.问题是因为您按输入分组,而不是按表中的行分组。

Also note that you appears to be using the same id on multiple elements, which is invalid.另请注意,您似乎在多个元素上使用相同的id ,这是无效的。 They have to be unique.它们必须是独一无二的。 Use a common class on them all instead.改为对它们使用通用类。 Then you can use map() to select the values from those fields like this:然后您可以使用map()从这些字段中选择值,如下所示:

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

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

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