Search code examples
javascriptappendchild

Populate table using submited form (javascript)


I am trying to learn javascript but so far i came to a complete stop. I've made a html webpage with a form on it (3 fields : Name ,Surname, Gender) and table below . i'm trying to list the data the user is typing in that form and display it below in the table using javascript (appendChild)

How could i do this easily? Examples are highly appreciated.

<HTML>
  <HEAD>
    <TITLE>Test1</TITLE>
    <META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=utf-8">
    <link rel="stylesheet" href="style.css" type="text/css" />

    <script language="javascript">


function addRow(){
...


    </script>

  </HEAD>
  <BODY>


<form>
Name:<br>
<input type="text" id="name"><br>
Last Name: <br> 
<input type="text" id="lname"><br>
Gender: <br>
<input type="text" id ="gender"> <br>
<input type="submit" id ="submit" value="Submit" onclick="addRow()">
</form> 


<table border="1">
<tr>
<th>Name</th>
<th>Last Name</th>
<th>Age</th>
</tr>
<tr>
<td>test, test</td>
<td>test, test</td>
</tr>
<tr>
<td>test2, test1</td>
<td>test2, test1</td>
</tr>
</table>


  </BODY>
</HTML>

Solution

  • Step 1:

    Give your table an identifier:

    <table border="1" id="results">
    

    Step 2:

    Get a DOM reference to this table:

    var table = document.getElementById('results');
    

    Step3:

    Make the elements you will insert:

    var row = document.createElement('tr');
    var td1 = document.createElement('td');
    var td2 = document.createElement('td');
    var td3 = document.createElement('td');
    

    Step4:

    Set their values:

    td1.innerHTML = document.getElementById('name').value;
    td2.innerHTML = document.getElementById('lname').value;
    td3.innerHTML = document.getElementById('gender').value;
    row.appendChild(td1);
    row.appendChild(td2);
    row.appendChild(td3);
    

    Step5:

    Insert into DOM:

    table.children[0].appendChild(row);
    

    Combined, we have:

    function addRow(){
        var table = document.getElementById('results');
        var row = document.createElement('tr');
        var td1 = document.createElement('td');
        var td2 = document.createElement('td');
        var td3 = document.createElement('td');
        td1.innerHTML = document.getElementById('name').value;
        td2.innerHTML = document.getElementById('lname').value;
        td3.innerHTML = document.getElementById('gender').value;
        row.appendChild(td1);
        row.appendChild(td2);
        row.appendChild(td3);
        table.children[0].appendChild(row);
    }
    

    If you want to prepend a row, you can use something like this:

    table.children[0].insertBefore(row,table.children[0].childNodes[1]);
    

    instead of using appendChild to append the row. The rest is the same. See this example.