Methods like click or trigger should be called after your dom elements are ready for the goal you want to achieve.
if your case, you tried to sort them by, the elements are completely loaded onto the page, so any solution that you try will simply not work, because we are missing something here.
Now consider this modified version of your getJson function:
$.getJSON(link, function(data) { usersData = data; // Table draw for (var i = 0; i < usersData.length; i++) { $("#users").append("<tr><td>" + usersData[i].id + "</td>" + "<td>" + usersData[i].name + "</td>" + "<td>" + usersData[i].username + "</td>" + "<td>" + usersData[i].email + "</td>" + "<td>" + usersData[i].address.street + "</td>" + "<td>" + usersData[i].address.suite + "</td>" + "<td>" + usersData[i].address.city + "</td>" + "<td>" + usersData[i].address.zipcode + "</td>" + "<td>" + usersData[i].address.geo.lat + "</td>" + "<td>" + usersData[i].phone + "</td>" + "<td>" + usersData[i].website + "</td>" + "<td>" + usersData[i].company.name + "</td>" + "<td>" + usersData[i].company.catchPhrase + "</td>" + "<td>" + usersData[i].company.bs + "</td></tr>") } // finished loading, now sort by name $(".sort.default").click(); });
Don't worry about this default class inside the jQuery selector described below :)
this is my approach to make it work:
1- I marked th by default, which you need to sort first with an extra class (with default name)
2- Then I added a call to simulate the click action after when the data is loaded (using a selector with a standard class into account)
// finished loading, now sort by name $(".sort.default").click();
and here is the link to the full working script: https://jsfiddle.net/hakeero/rfeh0q7v/1/
Mohammed ElSayed
source share