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?
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);
}
$(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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With