Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why the input feild value is not showing in the table?

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel


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++;
});

enter image description here

>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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading