英文:
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. I have three text box IDs such as morning
, noon
, and night
. I just want to store these values in an array like [morning, noon, night][morning, noon, night]...
.
I have tried, but it stored like [morning, morning, noon, noon, night, night]
. I can't understand how to separate as I mentioned above.
Please help me to solve my problem.
英文:
I have developed dynamically created text boxes by clicking a button
using AJAX. I have three text box IDs such as morning
, noon
and night
. I just want to store these values in an array like [morning, noon, night][morning, noon, night]...
I have tried, but it stored like [morning, morning, noon, noon, night, night]
. I can't understand how to separate as I mentioned above.
Please help me to solve my problem.
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
$(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);
});
});
<!-- language: lang-html -->
<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>
<!-- end snippet -->
答案1
得分: 2
问题是因为您按输入分组,而不是按表中的行分组。
还请注意,您似乎在多个元素上使用相同的 id
,这是无效的。它们必须是唯一的。而是在它们上面都使用一个共同的类。然后,您可以使用 map()
从这些字段中选择值,就像这样:
let modess = $('#rows tr').map(function() {
let $tr = $(this);
return [
$tr.find('.morning').val(),
$tr.find('.noon').val(),
$tr.find('.night').val(),
];
});
英文:
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. 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:
let modess = $('#rows tr').map(function() {
let $tr = $(this);
return [
$tr.find('.morning').val(),
$tr.find('.noon').val(),
$tr.find('.night').val(),
];
});
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论