I’m making a Dynamic HTML table using JavaScript, to which you can add first and last names. But when I click on the submit button, it creates empty cells without an input field value.
HTML
<input type="text" id="name" placeholder="First Name">
<input type="text" id="lastname" placeholder="Last Name">
<input type="button" id ="submit" value="Submit" >
<table border="1" id="table">
<tr>
<th>First Name</th>
<th>Last Name</th>
</tr>
</table>
JavaScript
let name = document.getElementById("name").value;
let lastname = document.getElementById("lastname").value;
let submit = document.getElementById("submit");
let table = document.getElementById("table");
var rowNum = 1;
submit.addEventListener("click" , function(){
var row = table.insertRow(rowNum);
var cell0 = row.insertCell(0);
var cell1 = row.insertCell(1);
cell0.innerHTML = name;
cell1.innerHTML = lastname;
rowNum++;
});
>Solution :
You need to get the inputs value after submit, not in the initial load of the script, as the values will be just empty string on script’s initial load.
You just need to add name and lastname variables inside the scope of the click event listener.
let submit = document.getElementById("submit");
let table = document.getElementById("table");
var rowNum = 1;
submit.addEventListener("click" , function(){
let name = document.getElementById("name").value;
let lastname = document.getElementById("lastname").value;
var row = table.insertRow(rowNum);
var cell0 = row.insertCell(0);
var cell1 = row.insertCell(1);
cell0.innerHTML = name;
cell1.innerHTML = lastname;
rowNum++;
});
<input type="text" id="name" placeholder="First Name">
<input type="text" id="lastname" placeholder="Last Name">
<input type="button" id ="submit" value="Submit" >
<table border="1" id="table">
<tr>
<th>First Name</th>
<th>Last Name</th>
</tr>
</table>
