1

I am trying to populate table data dynamically in JavaScript. I managed to populate it but there is some problem with the styling, here is what I have achieved so far:

enter image description here

And my code to achieve the above:

function populateOverallOverview(result){
    var tableData = new Array();
    var table = document.getElementById("firstTabOverall");

    for(var i = 0; i < result.length; i++){
        tableData[i] = new Array('Category: ' + result[i].category + '\n Best selling month: ' +  result[i].topMonthStr + '\n Amount: ' + result[i].topAmount.toFixed(2));
    }

    for(var i = 0; i < tableData.length; i++){
        var newRow = table.insertRow(table.length);
        for(var j = 0; j < tableData[i].length; j++){
            var cell = newRow.insertCell(j);

            cell.innerHTML = tableData[i][j];
        }
    }
}

My HTML code:

<div class="col-md-6">
    <table id="firstTabOverall" class="table table-striped" style="font-size:13px">
    </table>
</div>

What I wanted to achieve is for each row, there will be 3 different sub-rows for category, best selling month and amount. I am trying to split them into the next line using '\n' but it does not work.

Also, is there any way to bold the category, best selling month and amount wording in this case?

1
  • In this case, do I have to dynamically create some label or whatnot to style it accordingly? Other than using table, is it better to dynamically create div and append them together? Commented Sep 11, 2017 at 13:36

1 Answer 1

2

You do quite some unnecessary shifting-around of data. From results into a temp array, from the temp array into the table... why not from results straight into the table? Also, of course \n does not work. Line breaks mean nothing in HTML. You must add each cell individually.

The following looks a lot more straight-forward – and the Array#forEach() method rids you of the need for a separate loop counter, too:

function populateOverallOverview(result){
    var table = document.getElementById("firstTabOverall");

    // helper function        
    function addCell(tr, text) {
        var td = tr.insertCell();
        td.textContent = text;
        return td;
    }

    // insert data
    result.forEach(function (item) {
        var row = table.insertRow();
        addCell(row, 'Category: ' + item.category);
        addCell(row, 'Best selling month: ' + item.topMonthStr);
        addCell(row, 'Amount: ' + item.topAmount.toFixed(2));
    });
}

Instead of repeating the category names in front of the values, write them into the header row. That's how a table is supposed to work anyway, right?

So, maybe this is better:

function populateOverallOverview(result){
    var table = document.getElementById("firstTabOverall");

    // helper function        
    function addCell(tr, text) {
        var td = tr.insertCell();
        td.textContent = text;
        return td;
    }

    // create header 
    var thead = table.createTHead();
    var headerRow = th.insertRow();
    addCell(headerRow, 'Category');
    addCell(headerRow, 'Best selling month');
    addCell(headerRow, 'Amount');

    // insert data
    result.forEach(function (item) {
        var row = table.insertRow();
        addCell(row, item.category);
        addCell(row, item.topMonthStr);
        addCell(row, item.topAmount.toFixed(2));
    });
}

Use CSS to style your table and table header. It might be easier to just write the header row into the static HTML source up-front.


If you positively must add bold text inline labels, you could use these document.createElement("b"), to get a <b> element, set its .textContent and then use .appendChild() of the respective container, in this case of the table cell.

You can add plain text the same way - just use document.createTextNode('...your text...') instead and append that.

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

5 Comments

Thanks! However, I am trying to achieve something like for each main row (or you can take it as one div), the category, best selling month and amount should be in 3 separate rows. Then, perhaps I could style the div background color as well. But I not sure how to dynamically append the div, therefore I am using the table as alternative. Do you have any ideas?
I actually explain that in my answer. Read the last paragraph.
Building a DOM this way works, but it quickly becomes tedious. If you want to have more flexibility and much cleaner code, spend a few minutes to learn a templating framework. Look at handlebars.js, this is versatile and easy to pick up.
...of course a templating framework won't absolve you of learning how HTML itself works. It will only become useful on top of your HTML knowledge, so you need to work on that first.
Strange question... why would there not be a way to achieve this? But this exceeds the scope of this question and it's certainly out of scope for a discussion in the comments. The sparkline documentation has plenty of examples, start there. Ask a new question if you are unable to get it to work.

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.