jq实现表格的新增一行和删除一行
-
代码如下图:
<table id="dynamicTable" class="dynamicTable" width="100%" border="1" cellspacing="0" cellpadding="0">
<thead>
<tr>
<td width="5%" class="bg">序号</td>
<td width="15%" class="bg">被羁押人员姓名</td>
<td width="10%" class="bg">性别</td>
<td width="15%" class="bg">证件类型</td>
<td width="25%" class="bg">证件号码</td>
<td width="20%" class="bg">出生年月</td>
<td width="10%" class="bg" colspan="2">操作</td>
</tr>
<tr style="display: none">
<input type="hidden" id="NO" name="NO" data-no="2" />
</tr>
</thead>
<tbody id="shuju">
<tr>
<td align="center">1</td>
<td><input name="*erName" id="*erName1"/></td>
<td>
<select name="*erSex" id="*erSex1">
<option value="">-请选择-</option>
<option value="男" >男</option>
<option value="女" >女</option>
</select>
</td>
<td><input name="*erZjlxName" id="*erZjlxName1" value="身份证"/></td>
<td><input name="*erZjlxCode" id="*erZjlxCode1"/></td>
<td>
<input type="text" id="*erBirthDate1" name="*erBirthDate" readonly/>
</td>
<td><input type="button" class="addRow" onClick="addrow()" value="增加一行"></td>
<td><input type="button" class="deleteRow" onClick="deltr(this)" value="删除一行"></td>
</tr>
</tbody>
</table>
2. 动态增加一行jq代码如下图:
function addrow() {
var show_count = 10; //要显示的条数
var NO = $('#NO').attr('data-no'); //递增的开始值,这里是你的ID
var length = $("#dynamicTable tbody tr").length;
if (length < show_count) //点击时候,如果当前的数字小于递增结束的条件
{
var html = "<tr>"+
"<td align='center'>"+NO+"</td>"+
"<td><input id=*erName"+NO+" name='*erName'/></td>"+
"<td>"+
"<select id=*erSex"+NO+" name='*erSex' >"+
"<option value=''>-请选择-</option>"+
"<option value='男'>男</option>"+
"<option value='女'>女</option>"+
"</select></td>"+
"<td><input id=*erZjlxName"+NO+" name='*erZjlxName' value='身份证'/></td>"+
"<td><input id=*erZjlxCode"+NO+" name='*erZjlxCode'/></td>"+
"<td>"+
"<input type='text' id=*erBirthDate"+NO+" name='*erBirthDate' onclick='addDate("+NO+")' readonly/>"+
"</td>"+
"<td>"+
"<input type='button' class='addRow' onClick='addrow()' value='增加一行'>"+
"</td>"+
"<td>"+
"<input type='button' class='deleteRow' onClick='deltr(this)' value='删除一行'>"+
"</td>"+
"</tr>";
$("#dynamicTable >tbody").append(html);
var newNo=parseInt(NO)+1;
$('#NO').attr('data-no',newNo);
}
}
-
删除一行jq代码:
function deltr(opp) { var length = $("#dynamicTable tbody tr").length; if (length <= 1) { alert("至少保留一行"); } else { $(opp).parent().parent().remove();//移除当前行 changeIndex(); } }
效果图如下
开始的效果图:
点击增加一行后的效果图: