Search code examples
javascriptjqueryhtmlglyphicons

Add Glyphicon to Table Row Dynamically


I have a html table on my website that is displaying a live feed of data. I am retrieving this using a combination of PHP, MySQL and AJAX.

Table rows are being added to the table as new data is retrieved. Everything is working as expected.

I would like to add a glyphicon to a <td> depending on the contents of a javascript variable.

My html table is as follows;

<table id="transactionTable">
    <thead>
        <tr>
            <th>ID</th>
            <th>Date / Time</th>
            <th>Card No</th>
            <th>Direction</th>
        </tr>
    </thead>
</table>

The jquery that adds rows to the table;

$("#transactionTable").prepend('<tr><td>'+data.SerialNo+'</td><td>'+dateFormatted+'</td><td>'+data.CardNo+'</td><td id="direction">'+data.Direction+'</td></tr>');

What I want to do is,

// data.Direction is coming from the server

if(data.Direction == 'I') {
    // add <span class="glyphicon glyphicon-import"></span>
 }
if(data.Direction == 'O') {
    // <span class="glyphicon glyphicon-export"></span>
}

So the table rows should look like;

// if(data.Direction == 'I')
<tr>
    <td>1</td>
    <td>News</td>
    <td>News Cate</td>
    <td><span class="glyphicon glyphicon-import"></span> In</td>
</tr>

Or;

// if(data.Direction == 'O')
<tr>
    <td>1</td>
    <td>News</td>
    <td>News Cate</td>
    <td><span class="glyphicon glyphicon-export"></span> In</td>
</tr>

Any advice is appreciated.


Solution

  • Determine which icon you want to display, store it in a variable and add it to your the string you are passing into the prepend method.

    var iconHtml = '';
    
    if (data.Direction == 'I') {
        iconHtml = '<span class="glyphicon glyphicon-import"></span> ';
    }
    if (data.Direction === 'O') {
        iconHtml = '<span class="glyphicon glyphicon-export"></span> ';
    }
    
    $("#transactionTable").prepend('<tr><td>' + data.SerialNo +'</td><td>'+dateFormatted+'</td><td>'+data.CardNo+'</td><td id="direction">' + iconHtml +data.Direction+'</td></tr>');
    

    ```