簡體   English   中英

將動態創建的文本框值按順序存儲在 javascript 數組中

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

我通過使用 AJAX 單擊button開發了動態創建的文本框。 我有三個文本框 ID,例如morningnoonnight 我只想將這些值存儲在一個數組中,例如[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>

問題是因為您按輸入分組,而不是按表中的行分組。

另請注意,您似乎在多個元素上使用相同的id ,這是無效的。 它們必須是獨一無二的。 改為對它們使用通用類。 然后您可以使用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