javascript - 按顺序将动态创建的文本框值存储在 javascript 数组中
问题描述
我通过单击button
使用 AJAX 开发了动态创建的文本框。morning
我有三个文本框 ID ,例如noon
和night
。我只想将这些值存储在一个数组中[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(),
];
});
推荐阅读
- kubernetes - 解析 nginx 入口文件的 tls 部分时出错
- php - 在 php/mysql 中合计金额,当月至今
- javascript - 打字稿函数/对象参数
- spring-boot - 在测试中排除应用程序事件侦听器?
- angular - Auth0 通常要求用户进行两次身份验证
- twilio - Twilio - 通话和播放 mp3
- android - 在 Android Studio 的 build.gradle 中打印变量的简单方法?
- ios - Swift:如何使用 FairPlay 流媒体?
- ruby-on-rails - Rails 表单对象不使用多态关联更新数据库
- html - 最后的
- 去新行