How can I add a new row to a table with 3 input values?

I’m working on an expense tracker. I just want to write it in a way where I can add three different input values: name (string), date (number) and amount (number) to a new row once I click the add expense button.
This is as far as I can get with JS because I’m not sure how to add tr to a table with 3 different input values.

Here’s my HTML:

<body>

<div class="container">

<h2>Expense Tracker</h2>
<h3>Add New Item</h3>

<div class="input-item">
<label >Name</label>
<input type="text" id="myName">
</div>

<div class="input-item">
<label>Date</label>
<input type="number" id="myDate">
</div>

<div class="input-item">
<label>Amount</label>
<input type="number" id="myAmount"> 
</div>

<div class="button">
<button type="button" id="myButton">Add Expense</button>
</div>

<table class="table" id="myTable">
<tr>
  <th>Name</th>
  <th>Date</th>
  <th>Amount</th>
<tr/>
<tr>
  
</tr>
</table>
</div>
</body>

Here’s my JS

const nameInput = document.getElementById("myName");
const dateInput = document.getElementById("myDate");
const amountInput = document.getElementById("myAmount");
const addButton = document.getElementById("myButton");
const expenseTable = document.getElementById("myTable");

addButton.addEventListener('click', function(event){
const name = nameInput.value;
const date = dateInput.value;
const amount = amountInput.value;

});

You can create the elements or use a template literal and just write the HTML. Then insert it into the DOM using something like insertAdjacentElement or insertAdjacentHTML

An example using a template literal and insertAdjacentHTML. I remove the rest of the handler code for brevity.

const HTML = `
    <tr>
      <td>${name}</td>
      <td>${date}</td>
      <td>${amount}</td>
    </tr>
`;

expenseTable.insertAdjacentHTML("beforeend", HTML);

BTW, there is a date picker if that is what you want

It worked, thank you!

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.