我有长度是动态的表格/表格(用户可以添加/删除行)。我想创建一个 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
});
正在研究这个 fiddle http://jsfiddle.net/1jmjdxLL/
最佳答案
您可以使用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);
});
});
关于javascript - 根据用户输入的内容创建数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30574864/