Bart Simons

javascript

A 3 post collection


Creating HTML tables from JSON data in JavaScript

 •  Filed under json, data, html tables, javascript

A few weeks ago I have written a simple JavaScript library to convert JSON data to an HTML table, and vice versa if you need it. With that library comes even more functionality, like the ability to filter (search) through table rows and the ability to filter JSON data for a multi-page table layout.

You can find my project on GitHub.

This is the table and search box HTML code that I used for this article:

<div class="container">  
  <div class="row">
    <br>
    <input type="text" name="searchbox" id="searchbox" style="width: 100%;"><br><br>
  </div>

  <div class="row">
    <table id="userTable" class="table">
      <thead>
        <tr>
          <th>ID</th>
          <th>Name</th>
        </tr>
      </thead>
      <tbody>
        <tr>
          <td>1</td>
          <td>Bart</td>
       </tr>
        <tr>
          <td>2</td>
          <td>Nick</td>
        </tr>
        <tr>
          <td>3</td>
          <td>Jason</td>
        </tr>
        <tr>
          <td>4</td>
          <td>Fred</td>
        </tr>
        <tr>
          <td>5</td>
          <td>Ed</td>
        </tr>
        <tr>
          <td>6</td>
          <td>Peter</td>
        </tr>
      </tbody>
    </table>
  </div>
</div>  



So let's dive deeper into some code examples that you can use to create your tables from JSON data:


Example 1: Convert an HTML table to JSON

$(document).ready(function()
{
  // Create a new JSONTable Object from the basicTable table.
  var jsonTable = new JSONTable($("#basicTable"))

  // Convert existing HTML table to a JSON object.
  var tableData = jsonTable.toJSON()
})



Example 2: Search through a table with the filter function

$(document).ready(function()
{
  // Create a new JSONTable Object from the basicTable table.
  var jsonTable = new JSONTable($("#basicTable"))

  // Convert existing HTML table to a JSON object.
  var tableData = jsonTable.toJSON()

  // Create a jQuery event handler on the searchbox.
  $("#searchbox").on('input', function(e) {
    jsonTable.filter($(this).val())
  })
})



Example 3: Create a new HTML table directly from JSON data

// Build a JSON object array with items which are to be included in the table.
var jsonData = [{"ID":"1","Name":"User1"},{"ID":"2","Name":"User2"},{"ID":"3","Name":"User3"},{"ID":"4","Name":"Admin1"},{"ID":"5","Name":"Admin2"}]

// Create a new table inside the body tag
$("body").append("<table id='testTable'></table>")

// Spawn a new JSONTable object on the newly created table
var jsonTable = new JSONTable($("#testTable"))

// Create HTML table (data)structure from JSON data
jsonTable.fromJSON(jsonTest)  



You should definitely try these examples. Good luck!

Detect and monitor DOM changes with MutationObserver

 •  Filed under monitor, javascript, detect, dom changes, mutationobserver

The MutationObserver JavaScript API allows a developer to actively watch for DOM changes, so that if something gets changed, added or removed within the boundaries of the specified DOM node, a callback function will be triggered.

Browser support for this API is pretty good as well. All major modern browsers do support MutationObserver, but please note that IE10 and lower are not supported unless you use some sort of shim or polyfill for this.

Getting started is very easy as well:

// Step 1: Create a new MutationObserver object
var observer = new MutationObserver( function(mutations) { // this is the callback function } )

// Step 2: Observe a DOM node with the observer as callback
observer.observe(document.querySelector("table"), { attributes: true, childList: true, attributeOldValue: true })  



As an example I have built up a table to watch out for DOM changes:

<table id="demoTable" class="table">  
  <thead>
    <tr>ID</tr>
    <tr>E-mail</tr>
  </thead>

  <tbody>
    <tr>
      <td>1</td>
      <td>todd@localhost</td>
    </tr>
    <tr>
      <td>2</td>
      <td>ted@localhost</td>
    </tr>
    <tr>
      <td>3</td>
      <td>root@localhost</td>
    </tr>
    <tr>
      <td>4</td>
      <td>bart@localhost</td>
    </tr>
  </tbody>
</table>  



And here is the JavaScript code that goes with this:

var observer = new MutationObserver(function(mutation) {  
console.log(mutation)  
})

var observerConfig = {  
  attributes: true,
  childList: true,
  attributeOldValue: true,
  characterData: true
}

const tableRows = document.querySelectorAll("#appUsers tr")

for (i = 0; i < tableRows.length; i++)  
{
  observer.observe(tableRows[i], observerConfig);
}



Try to destroy, add or recreate td elements inside the table and you will get an array of MutationRecord objects returned within your browsers' console. Please note that when you edit the node's innerHTML, nothing will get triggered. I don't know if this is a bug in Safari (I only tested this in Safari, FYI) or something by design.

Bootstrap Tables to JSON, and vice versa.

 •  Filed under html, bootstrap, tables, json, jquery, javascript

This is just a quick post and/or announcement about a JavaScript library I have been working on:

github.com/bmsimons/bootstrap-jsontables

The main goal of this library is to make the link between a Bootstrap/HTML5 table with JSON a lot easier. Do you have an API available that returns data in JSON format? No problem! Bootstrap-jsontables takes care of that. Take a look at the examples on my GitHub repo if you need a quick visual glance of what this library could do for your project.


More features coming soon!

I'm having big plans to improve the search functionality of bootstrap-jsontables. The search functionality in its current form is just too simple, so that's going to be improved in the future.


Converting a table to JSON data

Say that we have this Bootstrap table:

<table id="appUsers" class="table">  
    <thead>
        <tr>
            <th>ID</th>
            <th>Name</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>1</td>
            <td>Bart</td>
        </tr>
        <tr>
            <td>2</td>
            <td>Nick</td>
        </tr>
    </tbody>
</table>  


Use this JavaScript/jQuery code to convert the table to JSON:

// Create a new JSONTable object on the #appUsers table.
var jsonTable = new JSONTable($("#appUsers"))

// Convert the table to JSON
var tableData = jsonTable.toJSON()

// The tableData object:
[{"ID":"1","Name":"Bart"}, {"ID":"2","Name":"Nick"}]



Keeping a log of all progress over here would be a bad choice, so please check out my GitHub for any future updates, changes and improvements:

https://github.com/bmsimons/bootstrap-jsontables

I hope that this library helps you with your project. Your feature requests and/or contributions are welcome, please let me and the community know in the form of a GitHub issue :)