使用JavaScript动态添加、删除表格
来源:程序员人生 发布时间:2014-05-26 08:43:19 阅读次数:2499次
效果图:
页面代码:
<table id="tabBill">
<tr>
<td colspan="2" align="center">
<input id="btnAddOne" onclick="Addtr();" type="button" value="增加项" />
<input id="btnRemoveOne" onclick="Removetr();" type="button" value="删尾行" />
</td>
</tr>
<tr>
<td>
故障代码 <asp:DropDownList ID="ddlFailureCode1" Width="196px" runat="server"/>
</td>
<td>
故障数 <asp:TextBox ID="txtFailureCodeAmount1" runat="server"/>
</td>
</tr>
</table>
JavaScript代码:
<script type="text/javascript" language="javascript">
var i=1;
var sub=true;
//添加行方法
function Addtr(){
i = tabBill.rows.length;
var ii = tabBill.rows.length;
var newTr = tabBill.insertRow(-1);
var newTd1= newTr.insertCell(-1);
var newTd2 = newTr.insertCell(-1);
//设置列内容和属性
newTd1.innerHTML = "故障代码 <select id='ddlFailureCode" + ii + "' style='width:196px'></select>";
newTd2.innerHTML = "故障数 <input type='text' id='txtFailureCodeAmount" + ii + "' class='tbStyle'/>";
AddOptions();
}
//删除行方法
function Removetr(){
if (tabBill.rows.length > 2)
{
tabBill.deleteRow(tabBill.rows.length - 1);
i--;
}
}
//添加选项
function AddOptions(){
var options = document.getElementById("ddlFailureCode1").options;
for (var m = 0; m < options.length; m++) {
var newOption = new Option(options[m].innerText, options[m].value);
document.getElementById("ddlFailureCode" + i).add(newOption);
}
}
//获取表单里面的值
function SaveHF(){
var subStr = "";
var count = tabBill.rows.length-1;
for (var n =1; n <= count; n++) {
var failureCode = document.getElementById("ddlFailureCode"+n).value;
var failureCodeAmount = document.getElementById("txtFailureCodeAmount"+n).value;
subStr += failureCode + "|" + failureCodeAmount+ "~";
}
//使用表单域保存得到的数据,"hfvalues"为表单域的ID
document.getElementById("hfvalues").value = subStr;
}
</script>
生活不易,码农辛苦
如果您觉得本网站对您的学习有所帮助,可以手机扫描二维码进行捐赠