getting error after executing the code TypeError: display is nullscript.js:22:22

Viewed 31

HTML This a HTML page I made to add row in the tables one by one below one another when user clicks on 'add' button and gives me error as below.

<div id="adder">
    <table id="adderhd">
        <tr>
            <th>PARTICULARS</th>
            <th>Amount</th>
        </tr>
        <tr>
            <th><input type="text" id="particulars" value=""></th>
            <th><input type="number" id="amount" value=""><button id="add">Add</button></th>
        </tr>
    </table>
</div>

<div id="tables">
    <div>
        <table class="table-1">
            <tr>
                <th>
                    PARTICULARS
                </th>
                <th>
                    AMOUNT
                </th>
            </tr>
        </table>
    </div>
</div>    

JavaScript This is a JavaScript code I wrote for it but after executing this I got error on console.

Please help me I am a beginner in JavaScript.

function rowAdder() {
    var particulars = document.getElementById("particulars").value;
    var amount = document.getElementById("amount").value;

    if (!particulars || !amount) {
        alert("Please enter the values inside all the field.");
        return;
    }

    var display = document.getElementById("table-1");    
    var newRow = display.insertRow(row);      //not working (insert(row)); 
    var cel1 = newRow.insertCell(0);
    var cel2 = newRow.insertCell(1);

    cel1.innerHTML = particulars;
    cel2.innerHTML = amount;    
    row++;

}
1 Answers

You need to add an event onclick on the button to call rowAdder function. Variable 'display' is getting element by id, so assign id="table-1" to your html element . Its working fine.

function rowAdder() {
  var particulars = document.getElementById("particulars").value;
  var amount = document.getElementById("amount").value;

  if (!particulars || !amount) {
    alert("Please enter the values inside all the field.");
    return;
  }

  var display = document.getElementById("table-1");    
  var newRow = display.insertRow();
  var cel1 = newRow.insertCell(0);
  var cel2 = newRow.insertCell(1);

  cel1.innerHTML = particulars;
  cel2.innerHTML = amount;    
}
  <div id="adder">
    <table id="adderhd">
        <tr>
            <th>PARTICULARS</th>
            <th>Amount</th>
        </tr>
        <tr>
            <th><input type="text" id="particulars" value=""></th>
            <th><input type="number" id="amount" value="">
            <button onclick="rowAdder()"id="add">Add</button></th>
        </tr>
    </table>
</div>

<div id="tables">
    <div>
        <table id="table-1">
            <tr>
                <th>
                    PARTICULARS
                </th>
                <th>
                    AMOUNT
                </th>
            </tr>
        </table>
    </div>
</div> 

Related