Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Updating Table rows using jQuery

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?

like image 365
Florian Mertens Avatar asked Jun 11 '13 12:06

Florian Mertens


2 Answers

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);
}
like image 183
asafreedman Avatar answered Sep 27 '22 21:09

asafreedman


$(function() {
    var objUser = {"id":2,"username":"j.smith","fname":"john","lname":"smith"};
    var objKeys = ["username", "fname", "lname"];

    $('#tr_' + objUser.id + ' td').each(function(i) {
        $(this).text(objUser[objKeys[i]]);
    });
});

jsFiddle code

like image 38
Shaddow Avatar answered Sep 27 '22 20:09

Shaddow