Orientation of a specific table in jQuery

I have the following code that works fine, except that it adds rows to every table on my page.

How to target a specific table in code?

$(document).ready(function() {
  $.getJSON('/api/getUsers',
    function(json) {
      var tr;
      for (var i = 0; i < json.length; i++) {
        tr = $('<tr/>');
        tr.append("<td>" + json[i].UserName + "</td>");

        // Format the phone number
        formatted_phone = json[i].PhoneNumber.replace(/(\d{3})(\d{3})(\d{4})/, '$1-$2-$3');

        tr.append("<td>" + formatted_phone + "</td>");
        tr.append("<td>" + json[i].Email + "</td>");
        tr.append("<td><button type=button class=\"btn btn-default btn-lg btn-block roster-button active\" data-toggle=modal data-target=#removeRoster>Remove</button></td>");
        tr.append("<td></td>");
        tr.append("<td><button type=button class=\"btn btn-default btn-lg btn-block roster-button active\" data-toggle=modal data-target=#updateTime>View/Update Time</button></td>");

        $('table').append(tr);
      }
    });
});
Run codeHide result
+4
source share
2 answers

You just need to add the identifier to your table and update the selector accordingly.

<table id="the-table">

Then change this line:

$('#the-table').append(tr);

If you want to apply this to several tables, but not to all, use a generic class instead of an identifier.

+4
source

. eq, id, class, .

<table class="tbl" id="tbl">

</table>

<script type="text/javascript">
$('table#tbl').append(tr);//using ID
$('table.tbl').append(tr);//using class
$('table:eq(0)').append(tr);//using zero based index
</script>

jQuery: https://api.jquery.com/category/selectors/

0

Source: https://habr.com/ru/post/1625575/


All Articles