0

When i try writing in textboxes the second time the window shows undefined, and if I try writing in the textboxes for the third time, it shows nothing.

I have a table that i wish to append a tablerow to. So when a button is clicked it will append a tr to a tbody, it works on the first click, but not on the second or third.

var expName = document.getElementById("expName");
var button = document.getElementById("button");
var amount = document.getElementById("amount");
var tbody = document.getElementById("tbody");
var date = document.getElementById("calendar");
var clear = document.getElementById("clear");

//print the tabledata
button.addEventListener("click", function() {
      expName = expName.value;
      amount = amount.value;
      date = date.value;
      var tr = document.createElement("tr");
      tr.innerHTML += "<td>" + expName + "</td>" + "<td>" + amount + "</td>" + "<td>" + date + "</td>";

      //set the value back to the original
      tbody.appendChild(tr);
      document.getElementById("expName").value = "";
      document.getElementById("amount").value = "";
      document.getElementById("calendar").value = "";

      //delte all table rows
      clear.addEventListener("click", function() {
        window.location.reload();

      })
<h1>Expense Tracker</h1>

<b>Item Name: </b><input type="text" id="expName">
<br/>
<br/>
<b>Amount: </b><input type="text" id="amount">

<b>Date: </b><input type="date" id="calendar">
<br/>
<br/>
<button id="button">add expense</button>
<button id="clear">Clear List</button>
<br/>
<br/>

<table id="table">
  <thead>
    <th>Name</th>
    <th>Amount</th>
    <th>Date</th>
  </thead>
  <tbody id="tbody"></tbody>
</table>
connexo
  • 53,704
  • 14
  • 91
  • 128
  • When you do `expName = expName.value`, you override the variable defined in the upper scope. Change this variable's name : `expNameValue = expName.value`. This also applies to `amount` and `date` – thchp Jan 21 '22 at 08:34
  • 1
    This question should be reopened, this has nothing to do with the duplicate. innerHTML is not called on the parent of the button holding the event listener – thchp Jan 21 '22 at 08:36
  • 1
    Pls fix the script error in your code. – connexo Jan 21 '22 at 08:41
  • 1
    `button.addEventListener` is not closed in the code provided. Depending on where you close it, it's probably the source of your issue. – Jeremy Thille Jan 21 '22 at 08:42

0 Answers0