2

This code retrieves the JSON data from the external source and displays it inside the table, it has total 50 rows of data, now I need to display the 1-10 rows, 11-20 rows .. until 40-50 rows when clicked on the respective row of the table, I've posted the whole jquery as it's a complex question to understand, any help will be apprecieated, thank you!

<table class="table table-hover" id="table" style="width:100%">
  <tbody>
    <tr>
      <th>ID</th>
      <th>FirstName</th>
      <th>LastName</th>
      <th>Username</th>
      <th>Avatar</th>
      <th>E-mail</th>
      <th>Age</th>
      <th>gender</th>
      <th>maritial status</th>
      <th>address</th>
      <th>Phone</th>
      <th>Website</th>
    </tr>
  </tbody>
</table>
$(document).ready(function() {
  fetch('http://fakeapi.jsonparseronline.com/users')
    .then(res => res.json())
    .then((out) => {
      console.log('Output: ', out);
    }).catch(err => console.error(err));

  $.getJSON('http://fakeapi.jsonparseronline.com/users',
    function(data) {
      var udata = '';

      $.each(data, function(key, value) {
        udata += '<tr>';
        udata += '<td>' + value.id + '</td>';
        udata += '<td>' + ' ' + value.firstName + '</td>';
        udata += '<td>' + ' ' + value.lastName + '</td>';
        udata += '<td>' + ' ' + value.username + '</td>';
        udata += '<td>' + ' ' + value.avatar + '</td>';
        udata += '<td>' + ' ' + value.email + '</td>';
        udata += '<td>' + ' ' + value.age + '</td>';
        udata += '<td>' + ' ' + value.gender + '</td>';
        udata += '<td>' + ' ' + value.maritalStatus + '</td>';
        udata += '<td>' + ' ' + value.address + '</td>';
        udata += '<td>' + ' ' + value.phone + '</td>';
        udata += '<td>' + ' ' + value.website + '</td>';
        udata += '</tr>';
      });
      $('#table').append(udata);

      $("#table tbody tr").click(function() {
        var $row = $(this).closest("tr");
        var $text = $row.find("td").text();
        alert($text);
      });
    });
});
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
cvz
  • 31
  • 7

1 Answers1

1

One solution is to make the listing snippet into a function that accepts a start and end parameter for which rows to display. Then you just need to figure out how to process those. In my example below, I just added an additional row with the text MORE that the user can press, and I use the row index to figure out what rows to display.

I've also used a local JSON variable since the resource you were fetching was inaccessible.

Edit: Now using a dropdown, removed local var.

$(document).ready(function () {
var users= [];
  
  $.getJSON('http://fakeapi.jsonparseronline.com/users', function(data) {
      users = data;
      buildSelect();
      listUsers(1, 10);
  });
  
  function buildSelect() {
      var sdata = "";
      $.each(users, function (key, value) {
        if (key % 10 === 0) {
          sdata += `<option data-start-index="${key + 1}" data-end-index="${key + 10}">${key + 1} - ${key + 10}</option>`;
        }
      });
      $(".more").html(sdata);
  }
  
  function listUsers(start, end) {
    var udata = "";
    
    $.each(users.slice(start-1, end), function (key, value) {
        udata += "<tr>" +
                     "<td>" + value.id + "</td>" +
                     "<td>" + value.firstName + "</td>" +
                     "<td>" + value.lastName + "</td>" +
                     "<td>" + value.username + "</td>" +
                     "<td>" + value.avatar + "</td>" +
                     "<td>" + value.email + "</td>" +
                     "<td>" + value.age + "</td>" +
                     "<td>" + value.gender + "</td>" +
                     "<td>" + value.maritalStatus + "</td>" +
                     "<td>" + value.address + "</td>" +
                     "<td>" + value.phone + "</td>" +
                     "<td>" + value.website + "</td>" +
                 "</tr>";
    }); 
    $('#table').html(udata);
  }
  
  $(document).on("change",".more",function() {
    listUsers($(":selected", this).attr("data-start-index"), $(":selected", this).attr("data-end-index"));
  });
});
.more {
  background-color: grey;
  text-align: center;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select class="more"></select>
<table class="table table-hover" id="table" style="width:100%"> 
<tbody>
    <tr>
      <th>ID</th>
      <th>FirstName</th>
      <th>LastName</th>
      <th>Username</th>
      <th>Avatar</th>
      <th>E-mail</th>    
      <th>Age</th>
      <th>Gender</th>
      <th>Maritial status</th>
      <th>Address</th>
      <th>Phone</th>
      <th>Website</th>
    </tr>
  </tbody>
</table>
cMarius
  • 1,090
  • 2
  • 11
  • 27
  • Hi, thank you so much for your submission. How to create a toggle dropdown for each 10 rows instead of a button? and also the JSON source works only without live preview – cvz Apr 26 '21 at 12:57
  • 1
    Sorry, I'm not sure I follow, what do you mean by dropdown menu? You would need an event to sometimes load an additional 10 products, right? How would the user trigger that event? – cMarius Apr 26 '21 at 13:00
  • 1
    I mean can we add a div/section for each 10 rows and display only those 10 rows when clicked on the div (just like how a dropdown menu works), and by default all the rows must be hidden – cvz Apr 26 '21 at 13:02
  • 1
    hmmm, we can try to replace `$('#table').append(udata);` with `$('#table').html(udata);`, and the way we get our row index. I've adjusted my answer to include 2 global vars `startIndex` and `endIndex`, and instead of getting the clicked tr index, we save our indexes in js vars. – cMarius Apr 26 '21 at 13:20
  • I need to add a drop-down at the top of the table and by default it should show the 1-10 data, and for the rest it should be selected from menu(11-20, 21-20 . . .) – cvz Apr 29 '21 at 09:42
  • 1
    I've added a new function that builds the `select` element based on the `users` variable, then changed the listener to work based on `change` events from the select. The `startIndex` and `endIndex` are added as data attributes on the options. Check my updated answer and let me know if it helps. – cMarius Apr 29 '21 at 13:14
  • Thanks a lot, this is what I was trying for, is that possible for you to help me add a pagination using JQuery for the same page? – cvz Apr 29 '21 at 13:25
  • And also please edit the JQuery function to fetch the data from external source. – cvz Apr 29 '21 at 13:38
  • 1
    I've edited my snippet to fetch the users data from an external source, as per your example, but if it works or not mostly depends on the response. As for pagination, that is a little more complicated and outside the scope of this question, try asking a new one or check out this resource for inspiration: https://stackoverflow.com/questions/19605078/how-to-use-pagination-on-html-tables/28206715 – cMarius Apr 29 '21 at 14:37
  • thank you so much, I can fetch the data from external source now, this really helped me. – cvz Apr 29 '21 at 14:39