-1

I recently started to code and I'm trying to build an expense application using HTML, CSS, and JavaScript. I'm creating a replica of this photo

Here is my HTML:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <link rel="stylesheet" type="text/css" href="css/style.css">
    <title>Expense Tracker</title>
</head>
<body>
    <h1>Expense Tracker</h1>
    
    <div id="myDiv">
        <label for="name">Name:</label>
        <input type="text" name="myInput" id="myInput" placeholder="Name of expense" size="50"><br><br>
        <label for="date">Date:</label>
        <input type="date" id="myDate" name="myDate">
        <label for="amount">Amount:</label>
        <input type="text" name="myAmount" id="myAmount" placeholder="Dollar amount ($)"><br><br>
        <span onclick="addRow()" class="addBtn">Add Expense</span>
    </div>
    <br>
    <table id="myTable">
      <tr>
        <th>Name</th>
        <th>Date</th>
        <th>Amount</th>
        <th>Delete</th>
      </tr>
      <tr>
        <td>McDonald's</td>
        <td>6/22/2017</td>
        <td>$12.00</td>
        <td><input type="button" value="Delete" onclick="deleteRow(this)"></td>
      </tr>
     </table>
    

    <script src="script.js"></script>
</body>
</html>

Here is my JavaScript, so far:

function deleteRow(r) {
  var i = r.parentNode.parentNode.rowIndex;
  document.getElementById("myTable").deleteRow(i);
}

How do I add additional rows using JavaScript? I can delete rows, using the JavaScript code above, but I am having a hard time figuring out how to add new elements.

adrvnc
  • 27
  • 1
  • 5

1 Answers1

1

You will need to do this via DOM manipulation. Something like this should work...

<button type="button" onclick="myFunction()">New row</button>
function myFunction() {
  var table = document.getElementById("myTable");
  var row = table.insertRow(0);
  var cell1 = row.insertCell(0);
  var cell2 = row.insertCell(1);
  cell1.innerHTML = "NEW CELL1";
  cell2.innerHTML = "NEW CELL2";
}
pixelcreated
  • 188
  • 9