I try to append a tr element to a tbody element, it works but when the tr is shown, the td is undefined, NaN and undefined. I try to get the value from the input elements and submit the tr of data to tbody.
Do you guys have any idea of where i went wrong?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Expense tracker remake</title>
</head>
<body>
<h1>Expense tracker</h1>
<div class="bold" id="name">Name of Item: </div> <input type="text">
<div class="bold" id="amount">Amount: </div> <input type="text">
<div class="bold" id="date">Date: </div> <input type="date">
<button id="submit">Submit</button> <button id="clear">Clear all</button>
<table>
<thead>
<th>Name</th>
<th>Amount</th>
<th>Date</th>
</thead>
<tbody id="tbody">
</tbody>
</table>
<script>
var tbody = document.getElementById("tbody");
var name = document.getElementById("name");
var amount = document.getElementById("amount");
var date = document.getElementById("date");
var clear = document.getElementById("clear");
var submit = document.getElementById("submit");
submit.addEventListener("click",function(){
var nameValue = name.value;
var amountValue = amount.value;
var dateValue = date.value;
var tr = document.createElement("tr");
tr.innerHTML += "<td>"+nameValue+ " </td><td>"+ + amountValue+ "</td><td>" + dateValue+ "</td>";
tbody.appendChild(tr);
console.log(name.value);
})
</script>
You have added an extra + in html string which you are using to append tr element.
tr.innerHTML += "<td>"+nameValue+ " </td><td>" + amountValue+ "</td><td>" + dateValue+ "</td>";
You made two mistakes:
Your name, amount and date elements are a divs, not an inputs, so when you trying to read from name.value you are trying to read from empty div.
Some words in javascript are reserved and sometimes when you using those your code could works in strange way. One of those words is name. Source.
The working demo of your code you can find here: jsFiddle.net.
As you can see, I've just pointed to input instead of div (by calling nextElementSibling because your input is a next element of your div) and changing variables names for avoiding name conflicts. Also, I have removed unnecessary doubled plus signs from tr.innerHtml += ....