软件下载 | 资讯教程 | 最近更新 | 下载排行 | 一键转帖 | 发布投稿
您的位置:最火下载站 > Web前端 > Ajax/JavaScript > 使用JavaScript动态添加、删除表格

使用JavaScript动态添加、删除表格

效果图:


页面代码:
<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>
                   故障代码&nbsp;<asp:DropDownList  ID="ddlFailureCode1" Width="196px" runat="server"/>
            </td>
            <td>
                  故障数&nbsp;<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 = "故障代码&nbsp;<select id='ddlFailureCode" + ii + "' style='width:196px'></select>";
            newTd2.innerHTML = "故障数&nbsp;<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>
    相关阅读
    栏目导航
    推荐软件