Updating Table rows using jQuery

Florian Mertens picture Florian Mertens · Jun 11, 2013 · Viewed 23.6k times · Source

Suppose you have a html table:

<table id="data">
    <thead>
        <tr>
            <td>ID</td>
            <td>Username</td>
            <td>First Name</td>
            <td>Last Name</td>
        </tr>
    </thead>
    <tbody>
        <?php foreach($arrData as $arrRecord) { ?>
        <tr id="tr_<?php echo $arrRecord["id"]; ?>">
            <td><?php echo $arrRecord["username"]; ?></td>
            <td><?php echo $arrRecord["fname"]; ?></td>
            <td><?php echo $arrRecord["lname"]; ?></td>
        </tr>
        <?php }?>
    </tbody>
</table>

And you have a JSON object:

objUser = {"id":12,"username":"j.smith","fname":"john","lname":"smith"};

And you want to change that record within the corresponding table row (assuming that this table already has a row with id="tr_12"):

$('#tr_' + objUser.id).find("td").eq(1).html(objUser.id);
$('#tr_' + objUser.id).find("td").eq(2).html(objUser.username);
$('#tr_' + objUser.id).find("td").eq(3).html(objUser.fname);
$('#tr_' + objUser.id).find("td").eq(4).html(objUser.lname);

Is there a faster/cleaner way of updating table rows using jQuery, than this last shown code block?

Answer

asafreedman picture asafreedman · Jun 11, 2013

I think there may be a couple things you could do

$('#tr_' + objUser.id).find("td").eq(1).html(objUser.id);
$('#tr_' + objUser.id).find("td").eq(2).html(objUser.username);
$('#tr_' + objUser.id).find("td").eq(3).html(objUser.fname);
$('#tr_' + objUser.id).find("td").eq(4).html(objUser.lname);

Could become:

$this = $('#tr_' + objUser.id).find("td");
$this.eq(1).html(objUser.id);
// And so on

You could do an outright replacements if it already exists

if ($('#tr_' + objUser.id).length) {
    var newHtml = '<td>' + .objUser.username + '</td>'
            + '<td>' + objUser.fname + '</td>'
            + '<td>' + objUser.lname + '</td>';
    $('#tr_' + objUser.id).html(newHtml);
}