1

I want to add json data to the table in HTML using vanilla javascript (no jquery) how can I do that ? below you will find the html code and the json data :

function myFunction() {
  // Declare variables
  var input, filter, table, tr, td, i;
  input = document.getElementById("myInput");
  filter = input.value.toUpperCase();
  table = document.getElementById("myTable");
  tr = table.getElementsByTagName("tr");

  // Loop through all table rows, and hide those who don't match the search query
  for (i = 0; i < tr.length; i++) {
    td = tr[i].getElementsByTagName("td")[0];
    if (td) {
      if (td.innerHTML.toUpperCase().indexOf(filter) > -1) {
        tr[i].style.display = "";
      } else {
        tr[i].style.display = "none";
      }
    }
  }
}
#myInput {
  background-image: url("/css/searchicon.png"); /* Add a search icon to input */
  background-position: 10px 12px; /* Position the search icon */
  background-repeat: no-repeat; /* Do not repeat the icon image */
  width: 100%; /* Full-width */
  font-size: 16px; /* Increase font-size */
  padding: 12px 20px 12px 40px; /* Add some padding */
  border: 1px solid #ddd; /* Add a grey border */
  margin-bottom: 12px; /* Add some space below the input */
}

#myTable {
  border-collapse: collapse; /* Collapse borders */
  width: 100%; /* Full-width */
  border: 1px solid #ddd; /* Add a grey border */
  font-size: 18px; /* Increase font-size */
}

#myTable th,
#myTable td {
  text-align: left; /* Left-align text */
  padding: 12px; /* Add padding */
}

#myTable tr {
  /* Add a bottom border to all table rows */
  border-bottom: 1px solid #ddd;
}

#myTable tr.header,
#myTable tr:hover {
  /* Add a grey background color to the table header and on hover */
  background-color: #f1f1f1;
}
<!doctype html>
<html>

<head>
    <meta charset="utf-8">
    <title>Table</title>
    <link rel="stylesheet" href="./assets/css/style.css">
    
</head>

<body>
    <input type="text" id="myInput" onkeyup="myFunction()" placeholder="Search for names..">

    <table id="myTable">
        <tr class="header">
            <th style="width:10%;">Picture</th>
            <th style="width:15%;">Name</th>
            <th style="width:5%;">Age</th>
            <th style="width:5%;">Active</th>
            <th style="width:20%;">Email</th>
            <th style="width:20%;">Phone</th>
            <th style="width:10%;">Company</th>
            <th style="width:10%;">Balance</th>
        </tr>
        <tr>
            <td><img src="http://placehold.it/32x32" alt=""></td>
            <td>Joseph Keller</td>
            <td>24</td>
            <td>true</td>
            <td>[email protected]</td>
            <td>+1 (827) 592-2357</td>
            <td>TWIIST</td>
            <td>$3,507.97</td>
        </tr>
    </table>
</body>
<script src="./assets/js/main.js"></script>

</html>

and here is part of json data that I want to appear in table :

    [
  {
    "_id": "5af5cf0270d455a211200d4c",
    "isActive": true,
    "balance": "$3,507.97",
    "picture": "http://placehold.it/32x32",
    "age": 24,
    "eyeColor": "brown",
    "name": "Joseph Keller",
    "gender": "male",
    "company": "TWIIST",
    "email": "[email protected]",
    "phone": "+1 (827) 592-2357",
    "address": "661 Terrace Place, Elliott, Ohio, 9927",
    "about": "Id sint labore sint dolore ex laboris. Ea irure dolor est nulla laboris Lorem sint fugiat laborum officia commodo. Reprehenderit culpa non voluptate ea. Fugiat duis et deserunt ea enim et ipsum nostrud commodo quis quis laborum officia. Elit est anim quis deserunt nulla nostrud ea eiusmod quis adipisicing. Mollit exercitation officia ipsum ea aliqua amet aliqua esse amet minim. Ipsum quis cillum fugiat reprehenderit sit aliquip aute in excepteur dolore fugiat esse non non.\r\n",
    "registered": "2014-12-10T07:18:10 +02:00",
    "latitude": -84.359436,
    "longitude": 156.008804,
    "tags": [
      "excepteur",
      "eiusmod",
      "laboris",
      "fugiat",
      "minim",
      "dolor",
      "qui"
    ],
    "friends": [
      {
        "id": 0,
        "name": "Shields Terrell"
      },
      {
        "id": 1,
        "name": "Hilary Bruce"
      },
      {
        "id": 2,
        "name": "Lorraine Torres"
      }
    ]
  }

can someone help ? I want to know how to do it using vanilla javascript

thank you

3
  • I wrote a json-to-html-converter. Have a look. It does what you want. niksofteng.github.io/json-to-html-converter/demo/index.html Commented Oct 5, 2018 at 18:35
  • thanks @nikhilVartak but the converter you gave converts all the data, I want it to be the same way as the table :) but thank you for sharing the link. I will save it in my favorite Commented Oct 5, 2018 at 18:39
  • 1
    So loop over the data and build the table rows... Commented Oct 5, 2018 at 18:41

2 Answers 2

2

I understand that you have a long JSON and you want to build a table like the one in your HTML. In this case you may try this:

let json =  [
  {
    "_id": "5af5cf0270d455a211200d4c",
    "isActive": true,
    "balance": "$3,507.97",
    "picture": "http://placehold.it/32x32",
    "age": 24,
    "eyeColor": "brown",
    "name": "Joseph Keller",
    "gender": "male",
    "company": "TWIIST",
    "email": "[email protected]",
    "phone": "+1 (827) 592-2357",
    "address": "661 Terrace Place, Elliott, Ohio, 9927",
    "about": "Id sint labore sint dolore ex laboris. Ea irure dolor est nulla laboris Lorem sint fugiat laborum officia commodo. Reprehenderit culpa non voluptate ea. Fugiat duis et deserunt ea enim et ipsum nostrud commodo quis quis laborum officia. Elit est anim quis deserunt nulla nostrud ea eiusmod quis adipisicing. Mollit exercitation officia ipsum ea aliqua amet aliqua esse amet minim. Ipsum quis cillum fugiat reprehenderit sit aliquip aute in excepteur dolore fugiat esse non non.\r\n",
    "registered": "2014-12-10T07:18:10 +02:00",
    "latitude": -84.359436,
    "longitude": 156.008804,
    "tags": [
      "excepteur",
      "eiusmod",
      "laboris",
      "fugiat",
      "minim",
      "dolor",
      "qui"
    ],
    "friends": [
      {
        "id": 0,
        "name": "Shields Terrell"
      },
      {
        "id": 1,
        "name": "Hilary Bruce"
      },
      {
        "id": 2,
        "name": "Lorraine Torres"
      }
    ]
  }
  ]

let _html = `<tr class="header">
            <th style="width:10%;">Picture</th>
            <th style="width:15%;">Name</th>
            <th style="width:5%;">Age</th>
            <th style="width:5%;">Active</th>
            <th style="width:20%;">Email</th>
            <th style="width:20%;">Phone</th>
            <th style="width:10%;">Company</th>
            <th style="width:10%;">Balance</th>
        </tr>`;

for(let i = 0; i < json.length; i++){
 _html += `<tr>
            <td><img src="${json[i].picture}" /></td>
            <td>${json[i].name}</td>
            <td>${json[i].age}</td>
            <td>${json[i].isActive}</td>
            <td>${json[i].email}</td>
            <td>${json[i].tel}</td>
            <td>${json[i].company}</td>
            <td>${json[i].balance}</td>
        </tr>`;
}

myTable.innerHTML = _html;




function myFunction() {
  // Declare variables
  var input, filter, table, tr, td, i;
  input = document.getElementById("myInput");
  filter = input.value.toUpperCase();
  table = document.getElementById("myTable");
  tr = table.getElementsByTagName("tr");

  // Loop through all table rows, and hide those who don't match the search query
  for (i = 0; i < tr.length; i++) {
    td = tr[i].getElementsByTagName("td")[1];
    if (td) {
      if (td.innerHTML.toUpperCase().indexOf(filter) > -1) {
        tr[i].style.display = "";
      } else {
        tr[i].style.display = "none";
      }
    }
  }
}
#myInput {
  background-image: url("/css/searchicon.png"); /* Add a search icon to input */
  background-position: 10px 12px; /* Position the search icon */
  background-repeat: no-repeat; /* Do not repeat the icon image */
  width: 100%; /* Full-width */
  font-size: 16px; /* Increase font-size */
  padding: 12px 20px 12px 40px; /* Add some padding */
  border: 1px solid #ddd; /* Add a grey border */
  margin-bottom: 12px; /* Add some space below the input */
}

#myTable {
  border-collapse: collapse; /* Collapse borders */
  width: 100%; /* Full-width */
  border: 1px solid #ddd; /* Add a grey border */
  font-size: 18px; /* Increase font-size */
}

#myTable th,
#myTable td {
  text-align: left; /* Left-align text */
  padding: 12px; /* Add padding */
}

#myTable tr {
  /* Add a bottom border to all table rows */
  border-bottom: 1px solid #ddd;
}

#myTable tr.header,
#myTable tr:hover {
  /* Add a grey background color to the table header and on hover */
  background-color: #f1f1f1;
}
<input type="text" id="myInput" onkeyup="myFunction()" placeholder="Search for names..">

    <table id="myTable"></table>

Sign up to request clarification or add additional context in comments.

4 Comments

thank you very much @enxaneta your code resolved the problem I was asking for, but after adding the code. my javascript code that I included in my post , doesn't work anymore. do you know how can I fix this problem ?
@AhmedHaiba: I've updated my answer by adding myFunction() to the javascript. I've changed td = tr[i].getElementsByTagName("td")[0]; with td = tr[i].getElementsByTagName("td")[1];and it works. 0 is for the image. 1 is for the name.
thank you very much, you resolved the problem perfectly :)
Decent use of template literals here... developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… check for supported browsers (no IE for example)
0

I do not know if you have parsed your data or not, so I assume so (if not there are tons of questions on how to do that). Here I process the "parsed" object inserting new rows for the data. Note I did leave the original row but that could be removed or otherwise handled.

Process the data, clone the row and put data in the row, then add it to the table.

I left your other functions in but did not know how to activated those, so they are just there for now.

var mythings = [{
  "_id": "5af5cf0270d455a211200d4c",
  "isActive": true,
  "balance": "$3,507.97",
  "picture": "http://placehold.it/32x32",
  "age": 24,
  "eyeColor": "brown",
  "name": "Joseph Keller0",
  "gender": "male",
  "company": "TWIIST",
  "email": "[email protected]",
  "phone": "+1 (827) 592-2357",
  "address": "661 Terrace Place, Elliott, Ohio, 9927",
  "about": "Id sint labore sint dolore ex laboris. Ea irure dolor est nulla laboris Lorem sint fugiat laborum officia commodo. Reprehenderit culpa non voluptate ea. Fugiat duis et deserunt ea enim et ipsum nostrud commodo quis quis laborum officia. Elit est anim quis deserunt nulla nostrud ea eiusmod quis adipisicing. Mollit exercitation officia ipsum ea aliqua amet aliqua esse amet minim. Ipsum quis cillum fugiat reprehenderit sit aliquip aute in excepteur dolore fugiat esse non non.\r\n",
  "registered": "2014-12-10T07:18:10 +02:00",
  "latitude": -84.359436,
  "longitude": 156.008804,
  "tags": [
    "excepteur",
    "eiusmod",
    "laboris",
    "fugiat",
    "minim",
    "dolor",
    "qui"
  ],
  "friends": [{
      "id": 0,
      "name": "Shields Terrell"
    },
    {
      "id": 1,
      "name": "Hilary Bruce"
    },
    {
      "id": 2,
      "name": "Lorraine Torres"
    }
  ]
}, {
  "_id": "5af5cf0270d455a211200d4c",
  "isActive": true,
  "balance": "$3,507.97",
  "picture": "http://placehold.it/32x32",
  "age": 24,
  "eyeColor": "brown",
  "name": "Joseph Keller1",
  "gender": "male",
  "company": "TWIIST",
  "email": "[email protected]",
  "phone": "+1 (827) 592-2357",
  "address": "661 Terrace Place, Elliott, Ohio, 9927",
  "about": "Id sint labore sint dolore ex laboris. Ea irure dolor est nulla laboris Lorem sint fugiat laborum officia commodo. Reprehenderit culpa non voluptate ea. Fugiat duis et deserunt ea enim et ipsum nostrud commodo quis quis laborum officia. Elit est anim quis deserunt nulla nostrud ea eiusmod quis adipisicing. Mollit exercitation officia ipsum ea aliqua amet aliqua esse amet minim. Ipsum quis cillum fugiat reprehenderit sit aliquip aute in excepteur dolore fugiat esse non non.\r\n",
  "registered": "2014-12-10T07:18:10 +02:00",
  "latitude": -84.359436,
  "longitude": 156.008804,
  "tags": [
    "excepteur",
    "eiusmod",
    "laboris",
    "fugiat",
    "minim",
    "dolor",
    "qui"
  ],
  "friends": [{
      "id": 0,
      "name": "Shields Terrell"
    },
    {
      "id": 1,
      "name": "Hilary Bruce"
    },
    {
      "id": 2,
      "name": "Lorraine Torres"
    }
  ]
}];

function processMyThings() {
  // console.log(mythings.length);
  for (var m = 0; m < mythings.length; m++) {
    let rowdata = mythings[m];
    //   console.log(mythings[m].name);
    addNewRow(rowdata);
  }
}

function addNewRow(rdata) {
  let tableId = "myTable";
  var table = document.getElementById(tableId);
  var clone = cloneRow(table);
  addDataToRow(clone, rdata);
  // clone.id = "newID"; // change id or other attributes/contents
  table.appendChild(clone); // add new row to end of table
}

function cloneRow(table) {
  var row = table.getElementsByClassName("row")[0];
  var clone = row.cloneNode(true);
  return clone;
}

function addDataToRow(clone, rdata) {
  //var tds = clone.getElementsByTagName("td");
  var image = clone.getElementsByClassName("rowimage")[0].getElementsByTagName('img');
  image.src = rdata.picture;
 // clone.getElementsByClassName("rowimage")[0].appendChild(image);
  clone.getElementsByClassName("rowname")[0].innerHTML = rdata.name;
  clone.getElementsByClassName("rowage")[0].innerHTML = rdata.age;
  clone.getElementsByClassName("rowactive")[0].innerHTML = rdata.active;
  clone.getElementsByClassName("rowemail")[0].innerHTML = rdata.email;
  clone.getElementsByClassName("rowphone")[0].innerHTML = rdata.phone;
  clone.getElementsByClassName("rowcompany")[0].innerHTML = rdata.company;
  clone.getElementsByClassName("rowbalance")[0].innerHTML = rdata.balance;
  return clone;
}

function createRow() {
  var row = document.createElement('tr'); // create row node
  var col = document.createElement('td'); // create column node
  var col2 = document.createElement('td'); // create second column node
  row.appendChild(col); // append first column to row
  row.appendChild(col2); // append second column to row
  col.innerHTML = "qwe"; // put data in first column
  col2.innerHTML = "rty"; // put data in second column
  var table = document.getElementById("tableToModify"); // find table to append to
  table.appendChild(row); // append row to table
}

function myFunction() {
  // Declare variables
  var input, filter, table, tr, td, i;
  input = document.getElementById("myInput");
  filter = input.value.toUpperCase();
  table = document.getElementById("myTable");
  tr = table.getElementsByTagName("tr");

  // Loop through all table rows, and hide those who don't match the search query
  for (i = 0; i < tr.length; i++) {
    // old: td = tr[i].getElementsByTagName("td")[0];
    let td = tr[i].getElementsByClassName("rowname")[0];
    if (td) {
      if (td.innerHTML.toUpperCase().indexOf(filter) > -1) {
        tr[i].style.display = "";
      } else {
        tr[i].style.display = "none";
      }
    }
  }
}
(function() {
  processMyThings();
})();
#myInput {
  background-image: url("/css/searchicon.png");
  /* Add a search icon to input */
  background-position: 10px 12px;
  /* Position the search icon */
  background-repeat: no-repeat;
  /* Do not repeat the icon image */
  width: 100%;
  /* Full-width */
  font-size: 16px;
  /* Increase font-size */
  padding: 12px 20px 12px 40px;
  /* Add some padding */
  border: 1px solid #ddd;
  /* Add a grey border */
  margin-bottom: 12px;
  /* Add some space below the input */
}

#myTable {
  border-collapse: collapse;
  /* Collapse borders */
  width: 100%;
  /* Full-width */
  border: 1px solid #ddd;
  /* Add a grey border */
  font-size: 18px;
  /* Increase font-size */
}

#myTable th,
#myTable td {
  text-align: left;
  /* Left-align text */
  padding: 12px;
  /* Add padding */
}

#myTable tr {
  /* Add a bottom border to all table rows */
  border-bottom: 1px solid #ddd;
}

#myTable tr.header,
#myTable tr:hover {
  /* Add a grey background color to the table header and on hover */
  background-color: #f1f1f1;
}
<input type="text" id="myInput" onkeyup="myFunction()" placeholder="Search for names..">

<table id="myTable">
  <tr class="header">
    <th style="width:10%;">Picture</th>
    <th style="width:15%;">Name</th>
    <th style="width:5%;">Age</th>
    <th style="width:5%;">Active</th>
    <th style="width:20%;">Email</th>
    <th style="width:20%;">Phone</th>
    <th style="width:10%;">Company</th>
    <th style="width:10%;">Balance</th>
  </tr>
  <tr class="row">
    <td class="rowimage"><img src="http://placehold.it/32x32" alt=""></td>
    <td class="rowname">Joseph Keller</td>
    <td class="rowage">24</td>
    <td class="rowactive">true</td>
    <td class="rowemail">[email protected]</td>
    <td class="rowphone">+1 (827) 592-2357</td>
    <td class="rowcompany">TWIIST</td>
    <td class="rowbalance">$3,507.97</td>
  </tr>
</table>

3 Comments

NOTE Jumping to an assumption, you probably want a better version of td = tr[i].getElementsByTagName("td")[0]; so with this you can search by name instead of the image? let td = tr[i].getElementsByClassName("rowname")[0]; Note this seems easier to maintain, and if you add more columns it does not need to change to keep searching by that name.
i adjusted as my comment indicates
that's right, now the code works perfectly. thanks a lot for your effort

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.