how to create dynamic row with input fields in html table from given row

前端 未结 3 1486
醉话见心
醉话见心 2021-01-17 06:53

Im new for Html and javascript. I want to create dynamic row with input fields in table while click button,that number of row given from user. In my code, row created dynami

3条回答
  •  太阳男子
    2021-01-17 07:01

    Use Element.appendChild instead of innerHTML

    • Element.firstChild will return first-child of the element.
    • querySelectorAll will return NodeList as per the specified selector.
    • Element.appendChild will append new Node in the Element without affecting existing content in the Element.

    function createTable() {
      var a = document.getElementById('tb1').value;
      if (a == "") {
        alert("Please enter some numeric value");
      } else {
        var th = document.querySelectorAll('#table th');//To check whether `TD` is appended in table or not!
        if (!th.length) {
          //If not appended, then append TD in table
          var rows = "Item NameQuantityQuantityTypeAmount";
          var table = document.createElement('table');
          table.innerHTML = rows;
          document.getElementById("table").appendChild(table.firstChild);
        }
    
        for (var i = 0; i < a; i++) {
          var elems = '';
          elems += "";
          var table = document.createElement('table');
          table.innerHTML = elems;
          document.getElementById("table").appendChild(table.firstChild);
        }
      }
    }
    div {
      background: red;
      margin: 5px;
    }
    table {
      border: 2px solid black;
    }
    td {
      padding: 10px;
      border: 1px solid lightgrey;
    }
    
    
    

提交回复
热议问题