Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

266
Visualizações
Why is the input field value 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

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

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

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>

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda