根据用户输入的输入创建数组
问题描述:
我有表格/表格,其中的长度是动态的(用户可以添加/删除行)。我想创建一个数组onsubmit,其中包含用户输入的值,并使用console.log
来显示数组值和数组长度。根据用户输入的输入创建数组
HTML
<div class="container">
<form id="online1" action="#">
<table class="table" id="tblData">
<thead>
<tr>
<th>Youtube ID</th>
<th>Add/Delete</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<input type="text" class="form-control song-input" placeholder="5YCcad6hklE" />
</td>
<td>
<button type="button" class="btn btn-default btn-add">Add</button>
</td>
</tr>
<tr>
<td>
<input type="text" class="form-control" placeholder="t6Lr8ggJWi4" />
</td>
<td>
<button type="button" class="btn btn-danger btn-del">Del</button>
</td>
</tr>
<tr>
<td>
<input type="text" class="form-control" placeholder="YmzfaapaPMA" />
</td>
<td>
<button type="button" class="btn btn-danger btn-del">Del</button>
</td>
</tr>
</tbody>
</table>
<button type="button" class="btn btn-primary">Submit</button>
</form>
jQuery的
jQuery(".btn-primary").click(function(){
var values = [];
$('.yt-mix').each(function() {
values[this.name] = this.value;
});
var mix_size = values.length;
console.log(values); // "5YCcad6hklE", "t6Lr8ggJWi4", "YmzfaapaPMA"
console.log(mix_size); // 3 rows
});
答
您可以使用each
遍历所有文本框。 :text
伪选择器选择所有文本框。
$(document).ready(function() {
$(document).on('click', '.btn-primary', function() {
var values = [];
$('#tblData :text').each(function() {
if ($(this).val()) {
values.push($(this).val());
}
});
console.log(values);
console.log(values.length);
});
});
+0
谢谢,只需要在'.btn-primary'然而按下它开火:) – abracassabra
+0
@LordTubington你走了。更新了答案 – Tushar
答
$(".btn-primary").click(function(){
var values = [];
$('#tblData input').each(function() {
values.push($(this).val());
});
var mix_size = values.length;
console.log(values); // "5YCcad6hklE", "t6Lr8ggJWi4", "YmzfaapaPMA"
console.log(mix_size); // 3 rows
});
'警报($( “#tblData TBODY TR”)的长度。)' –