【发布时间】:2017-09-19 17:28:49
【问题描述】:
我有一个带有页眉和页脚的表格,并且已经创建了一个默认行。当我动态添加更多行时,我没有得到确切的行数。如果我之前添加它们,它总是返回正确的行数。
下面是我写的代码-
<table id="empTable" class="table table-responsive table-striped table-bordered">
<thead>`enter code here`
<tr>
<td>Name of Employee</td>
<td>Father's Name/Husband's Name</td>
<td>Basic</td>
<td>Total attendance</td>
<td>Clear</td>
</tr>
</thead>
<tbody id="TextBoxContainer">
<tr>
<td><input id="emp_name" name="DynamicTextBox" type="text" value="" class="form-control" /></td>
<td><input id="father_name" name="DynamicTextBox" type="text" value="" class="form-control" /></td>
<td><input name="DynamicTextBox" type="number" value="" class="form-control" /></td>
<td><input name="DynamicTextBox" type="number" value="" class="form-control" /></td>
<td><button type="button" class="btn btn-danger remove"><i class="glyphicon glyphicon-remove-sign"></i></button></td>
</tr>
</tbody>
<tfoot>
<tr>
<th colspan="5">
<button id="btnAdd" type="button" class="btn btn-primary" data-toggle="tooltip" data-original-title="Add more controls"><i class="glyphicon glyphicon-plus-sign"></i> Add </button></th>
</tr>
</tfoot>
</table>
<script>
//function to add/remove rows
$(function() {
$("#btnAdd").bind("click", function() {
var div = $("<tr />");
div.html(GetDynamicTextBox(""));
$("#TextBoxContainer").append(div);
});
$("body").on("click", ".remove", function() {
$(this).closest("tr").remove();
});
});
//function to return value of Dynamic content
function GetDynamicTextBox(value) {
return '<td><input name="DynamicTextBox" type="text" value="" class="form-control" /></td>' +
'<td><input name="DynamicTextBox" type="text" value="' + value + '" class="form-control" /></td>' +
'<td><input name="DynamicTextBox" type="number" value="' + value + '" class="form-control" /></td>' +
'<td><input name="DynamicTextBox" type="number" value="' + value + '" class="form-control" /></td>' +
'<td><button type="button" class="btn btn-danger remove"><i class="glyphicon glyphicon-remove-sign"></i></button></td>'
}
</script>
我正在使用这条线返回行数,但它不起作用 -
var rowCount = document.getElementById("TextBoxContainer").rows.length;
$('#btnSave').on('click', function() {
alert(rowCount);
})
我已经尝试了 stackoverflow 的所有解决方案,但不明白为什么它不适用于动态行,而我在小提琴中看到的相同代码有效。
请帮忙。
【问题讨论】:
-
在任何地方都看不到
id=btnSave。也许#btnAdd? -
为什么不直接使用 jQuery 来获取行数呢? var rowCount = $('#TextBoxContainer tr').length;
-
@AlonEitan #btnAdd 添加行。 #btnSave 只是为了测试警报的行数。
-
@HaukurHaf 我已经试过了。即使我添加更多行,它也只会返回计数为 1。但是,如果我在(静态)之前添加行,相同的代码会给出准确的计数。不确定动态计数有什么问题。
-
完成。也感谢您的宝贵时间:)
标签: javascript jquery