How to Manipulate and fill HTML Table - JavaScript & jQuery

Manipulate and fill HTML Table

1- Fill table by using jQuery append method. 

  • Table Structure
<table id="names">
    <tr>
        <th>First Name</th>
        <th>Last Name</th>
    </tr>

</table>
  • Code to append data from json 
var jsonNames = { "Mohamed": "saad", "joseph": "Dankwah", "Christian": "mensah" };

$.each(jsonNames, function (key, val) {
    $("<tr><td>" + key + "</td><td>" + val + "</td</tr>").appendTo("#names")

});


See the Pen appendTo from json by Mohamed Salah (@saad306) on CodePen.

2- Fill table by retrieving data from user input .  

  • Here is html structure 
<div>
    <label>First Name : <input id="frist-name" type="text" /></label>
    <br /> <br />
    <label>Last Name : <input id="last-name" type="text" /></label>
    <br /><br />
    <input type="button" value="Add Name" onclick="addname()" />
</div>

<br /><br />

<table id="names">
    <tr>
        <th>First Name</th>
        <th>Last Name</th>
        <th>Full Name</th>
    </tr>

</table>>
  • And your Code 
function addname() {
    var fName = $("#frist-name").val().toUpperCase();
    var lName = $("#last-name").val().toUpperCase();
    if (fName != "" && lName != "") {
        $("<tr><td>" + fName + "</td><td>" + lName + "</td><td>" + fName + " " + lName + "</td></tr>").appendTo("#names")
    }

}

  • Try It .. 
See the Pen appendTo from input by Mohamed Salah (@saad306) on CodePen.