Maltesse Maltesse - 4 months ago 20
jQuery Question

Sorting data to the HTML tables by their ID jQuery/javaScript

I have an iteresting problem and I was trying to solve it for days.

I have a jQuery script which takes JSON object from the url and then put it into the array. The problem occurs when I have 3 different tables and script puts the data into 3 of them. I was trying to sort it by #id recognision, but it wasn't working at all.

This is a script which takes data from the server.
The JSON object is:

[{"Date": 20160721, "Failures": 5, "Hostname": "AIX", "Scan policy": "compliance-rhel6-int-prd"}, {"Date": 20160721, "Failures": 1, "Hostname": "Linux", "Scan policy": "compliance-rhel6-int-prd"}]


Script:

<script>
var url = 'http://jsonobj/_server_data'
$.getJSON(url,
function (data) {
var tr;
for (var i = 0; i < data.length; i++) {
tr = $('<tr/>');
tr.append("<td>" + data[i].Date + "</td>");
tr.append("<td>" + data[i].Failures + "</td>");
tr.append("<td>" + data[i].Hostname + "</td>");
$('table').append(tr);
}
});
</script>


What I am trying t o do is create two tables one for AIX one for Linux and store the data for that systems only. Right now the same data appears in two tables.
I was t rying to sort it by getting
$.(#hostname)
as ID, but it didn't work.

Thank you for your help!

Answer

Just have 2 tables on the page. One with the id of #AIX and the other with the id of #Linux

HTML:

<table id="AIX"></table>
<table id="Linux"></table>

Javascript:

<script>
    var url = 'http://jsonobj/_server_data'
    $.getJSON(url,
            function (data) {
                var tr;
                for (var i = 0; i < data.length; i++) {
                    tr = $('<tr/>');
                    tr.append("<td>" + data[i].Date + "</td>");
                    tr.append("<td>" + data[i].Failures + "</td>");
                    tr.append("<td>" + data[i].Hostname + "</td>");

                    // This is where the magic happens
                    $('table#' + data[i].Hostname).append(tr);
                }
            });
</script>

Doing this, the tr elements will be appended only to the table which matches the ID of the hostname.