0

Firstly, apologies for any rather haphazard or completely silly coding no-no's. As this is a first attempt at doing something like this for me. So I'm kind of learning on the fly.

I'm attempting to use JQuery. $.each() to iterate through a JSON object, that has been returned using an Ajax call, to build a table of the results of a search.

The results and as such, the table, will have varying quantities of fields depending upon the type of search that the user has entered. The below example is contains only 3 fields, whereas other searches can be as many as 8 fields.

An example structure of the JSON object that my server side script returns for one type of search is as follows:

{"header": 
    {"0": "DRAWING_ID", "1": "FILENAME", "2": "LAST UPDATED"}, 
"results": 
    {"1": {"DRAWING_ID": "15682", "LAST UPDATED": "2015-02-27 10:50:47", "FILENAME": "10-22-2008-K_Shared Sports Analysis Tools"}, 
     "2": {"DRAWING_ID": "7162", "LAST UPDATED": "2015-02-10 07:42:55", "FILENAME": "10-22-2001-BT_Salt And Pepper"}, 
     "3": {"DRAWING_ID": "20429", "LAST UPDATED": "2015-01-26 11:19:40", "FILENAME": "10-22-2006-G_Public Area Fibre"}, 
     "4": {"DRAWING_ID": "7163", "LAST UPDATED": "2014-12-01 23:20:57", "FILENAME": "10-22-2003-AL_Ref Dist"}, 
     "5": {"DRAWING_ID": "17265", "LAST UPDATED": "2013-11-11 16:07:56", "FILENAME": "10-22-2009-B_ Shared Area Monitor"}}}

I have chosen to separate out the header and fields and then use the values from the header as keys for the results.

Using JQuery I have been able to draw the HTML table <th> elements for the headers using $.each() successfully. Yet have been unable to get the same outcome for the results.

The code snippet from drawTable() for the <th> section is as follows:

function drawTable( data ) {
    $("#resultsTable").empty();
    $("#resultsTable").append(function(){
          $.each(data.header, function(index, element) {
            console.log(index,element)
            $("#resultsTable").append($("<th>").text(data.header[index]));
          });
        }).wrapInner("<tr></tr>");

Each time this drawTable function is called by the Ajax callback, it empties the last table and redraws. The result of the above is:

<table class="table table-hover table-condensed" id="resultsTable">
    <tr><th>DRAWING_ID</th><th>FILENAME</th><th>LAST UPDATED</th></tr>
</table>

The results data has given me the biggest problem and I have not been able to puzzle of how to fix it. The last snippet of drawTable() which deals with the remaining rows of the table is as follows:

$.each(data.results, function(index, element) {
            console.log(element)
            $("#resultsTable").append($("<tr>").text(function(){
                $.each(element, function(index2, element2) {
                    console.log(element2)
                    $("<td>").text(element2);
                })
            }));
        });

Which results in a bunch of empty rows:

<tbody>
    <tr></tr><tr></tr><tr></tr><tr></tr><tr></tr><tr></tr><tr></tr><tr></tr>
</tbody>

I have tried this in a slightly different way which results in all of the <td> cells on a single row. But I cannot seem to get them to be wrapped by each of the <tr></tr> rows.

Actually, I have been able to successfully draw a similar table by directly indexing each cell that needs to be appended to the table and then wrapping the entire lot in the <tr></tr>. Like this:

$.each(data.design.results, function(index, element) {
          $("#resultsTable").append($("<tr>").append(
          console.log(data.design.results[index]),
          $("<td>").text(data.design.results[index].LOCATION),
          $("<td>").text(data.design.results[index].SYSN),
          $("<td>").text(data.design.results[index].MODEL),
          $("<td>").text(data.design.results[index].FUNCTION)).attr('onclick', 'cardDetails("'+ data.design.results[index].SYSN +'")'))
        });

But in this separate instance, where the result will vary in number of fields I can't see that as being the best approach. I think I am most struggled with getting the nested $.each() element working at first.

Any help on this would be greatly appreciated.

Thanks all.

2
  • jsfiddle.net/ukm826br/1 Commented Mar 3, 2015 at 10:14
  • Thanks Mohit. Unfortunately using specific key's I.e. "DRAWING_ID" and "FILENAME" to obtain the cell value will only work for this response. Not all JSON responses returned will contain these fields. For example, this is a separate response for a different search: {"header": {"0": "SYSN", "1": "BRAND", "2": "MODEL", "3": "FILENAME"}, "results": {"1": {"BRAND": "AXON", "SYSN": "44/SYNC001", "MODEL": "GXG010+BPH17_GXG010", "FILENAME": "44-22-2001-Q_SYS2_SKY_1_SPORTS_5_Mixer Systems_HD"}}} Commented Mar 3, 2015 at 10:44

1 Answer 1

1

Maybe you could save the header fields in a separate var, and build the rows according to it? E.g.:

function drawTable( data ) {
    $("#resultsTable").empty();
    var fieldMapping = {};
    $("#resultsTable").append(function(){
      $.each(data.header, function(index, element) {
        $("#resultsTable").append($("<th>").text(data.header[index]));
          fieldMapping[data.header[index]]=index;
      });
    }).wrapInner("<tr></tr>");

    $.each(data.results, function(index, element) {
            var tr=$('<tr/>');
            for(key in fieldMapping)
                tr.append('<td>'+element[key]+'</td>');
            $("#resultsTable").append(tr);
        });
}

Fiddle demo: http://jsfiddle.net/1uz3w6ou/

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

Comments

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.