Search code examples
javascripttextbox

Trying to add textbox values as a table row


I´m trying to read 3 textbox values: first name, last name and age, and adding them after clicking the save button as a row in a table, but it isn't working. What's wrong with my function?

function save()
{ 
var firstName= document.getElementById("txtFname").value;
var lastName=document.getElementById("txtLname").value;
var ageValue=parseInt(document.getElementById("age").value,10);

var table2=document.getElementById("dbtable");
var fNameValue= value.createTextNode(firstName);
var lNameValue= value.createTextNode(lastName);
var agetextnode=value.createTextNode(ageValue);

td1=document.createElement("td");
td2=document.createElement("td");
td3=document.createElement("td");

td1.appendChild(fNameValue);
td2.appendChild(lNameValue);
td3.appendChild(agetextnode);

tr1=document.createElement("tr");
tr1.appendChild(td1);
tr1.appendChild(td2);
tr1.appendChild(td3);

table2.appendChild(tr1);
}

Solution

  • It helps if you can provide the full HTML/JavaScript being used so we can see where the issue is.

    I would also recommend spreading out your logic to make it easier to troubleshoot. You essentially have 3 steps:

    1. Obtain the entered values
    2. Generate the markup for the new row
    3. Append the row to the table

    Here's an example how those could look with your requirements.

    function save () {
      const age = document.getElementById('age').value;
      const first = document.getElementById('firstName').value;
      const last = document.getElementById('lastName').value;
      const tbody = document.querySelector('#dtable tbody');
      tbody.appendChild(createRow(age, first, last));
    }
    
    function createRow(age, first, last) {
      const tr = document.createElement('tr');
      tr.appendChild(createTd(age));
      tr.appendChild(createTd(first));
      tr.appendChild(createTd(last));
      return tr;
    }
    
    function createTd(value) {
      const td = document.createElement('td');
      td.innerText = value;
      return td;
    }
    table {
      width: 100%;
    }
    <input type="number" id="age" placeholder="age" />
    <input type="text" id="firstName" placeholder="First Name" />
    <input type="text" id="lastName" placeholder="Last Name" />
    <button onclick="save()">Save</button>
    
    <table id="dtable">
      <thead>
        <tr>
          <th>Age</th>
          <th>First</th>
          <th>Last</th>
        </tr>
      </thead>
      <tbody>
      </tbody>
    </table>