Dynamically Create HTML Table with Pagination - javascript

I'm trying to create an html table with pagination. I'm requesting JSON data via $.get call using JQuery which is an async call. The solution I currently have duplicates the HTML code whenever a new page is selected. I know this is an asynchronocity but I'm not exactly sure what the best method to overcome this would be.
<script type="text/javascript">
function generateTable(currentPage) {
this.URL = "https://jsonplaceholder.typicode.com/posts";
$.getJSON(URL, function(data) {
const pages = Math.ceil(data.length / 10);
for(let i = currentPage*10; i<(currentPage*10)+10; i++ ) {
let post = data[i];
let tblRow = "<tr>" + "<td>" + post.userId + "</td>" + "<td>" + post.id + "</td>" + "<td>" + post.title + "</td>" + "<td>" + post.body + "</td>" + "</tr>"
$(tblRow).appendTo("#jsonData tbody");
}
for (let i = 1; i <= pages; i++) {
let pagingHtml = "<a href=# onclick=generateTable("+(i-1)+")>"+" "+i+" "+"</a>"
$(pagingHtml).appendTo("#paging");
}
})
}
generateTable(0);
</script>

Before populating the HTML, clear out the current rows from the page:
$("#jsonData tbody,#paging").empty();
This assumes that those two parent elements only have dynamic content. If not, you should reference container elements that only have dynamic content (so no headers, footers, ...etc).

Related

I am working on appending row in javascript but I actually don't know how to append an image in row cell

[I am appending a row. everything appended but image not showing. I tried some ways but cant solve this problem][1]
function SearchDrivers() {
var Id = document.getElementById('driverSearch').value;
$.ajax({
url: "/Administration/SearchDrivers/" + Id,
type: "Get",
contentType: "application/json;charset=UTF-8",
dataType: "json",
success: function (response) {
var table = document.getElementById('DriverTable');
var drivers = response['users'];
for (var j = 0; j <= drivers.length; j++) {
var driver = drivers[j];
tr = "<tr>"
+ "<td>" + driver['email'] + "</td>"
+ "<td>" + driver['email'] + "</td>"
+ "<td>" + "033138445156666" + "</td>"
+ "<td>" + "<button class='table-btn'>unverified</button>" + "</td>"
this is the way i am appending an image and its style. I used some more ways to append a image but thay also not working for me.
+ "<td>" + "<a asp-action='DriverProfile'><img class='ml-2 icon-15' src='~/svg/visibility.svg'></a>" + "</td>"
+ "</tr>";
$('#DriverTable tbody').append(tr);
}
}
});
}
Your svg folder should be placed under wwwroot.
Then you need to change your path to
<img class='ml-2 icon-15' src='/svg/visibility.svg'></a>
Delete the ~.

Need help referencing elements

I know I'm asking really simple questions but I'm a beginner and it the process of learning. I've got this code but I don know how to make it work. The output i expect is upon clicking the button it activates function insertAfter and adds text/paragraph that ill write.
I've tried: onclick='insertAfter(test,index.this)'
It didn't work and consoled said it was undefined.
var content = "";
Applications.forEach(generatetable);
function testfn(index, tdElement) {
console.log(tdElement.parentElement);
console.log(index);
console.log(Applications[index].Name);
}
function generatetable(item, index, arrays) {
var columns = "";
columns = columns + "<td onclick='testfn(\"" + index + "\", this)'>" + "<button onclick='insertAfter(test?,???)' type=\"button\">Click Me!</button>" + item.UAID + "</td>";
columns = columns + "<td>" + item.Name + "</td>";
columns = columns + "<td>" + "<a href='www.wahtever.com'>map</a>" + "</td>";
content = content + "<tr>" + columns + "</tr>";
}
var test = "<tr><td>fsdf</td></tr>";
document.getElementById("table").innerHTML = content;
function insertAfter(newNode, referenceNode) {
referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);
}
It is supposed to insert a paragraph preferably what i put in the test variable but if there is better is better solution please let me know.
<button onclick='insertAfter(test,ElementID)>
The second refference node (ElementID) should be be the id of the element after which it is to be put. So it has to be somehow refferenced for example by id.

Sort HTML Table, that gets appended via JQuery

Hello i'm trying to use Tablesorter(https://github.com/christianbach/tablesorter) to sort a table of mine which i generate throu JQuery.appends. This is how my code looks:
$(document).ready(function() {
*Lotsa more code .....*
$.get("../skillqueue",{keyid: keyid, charid: charid},function(xmlskillqueue){
console.log("XML Skillqueue");
console.log(xmlskillqueue);
//Variables for
var rowsets = xmlskillqueue.getElementsByTagName("rowset");
var skillrows;
for(var i = 0; i < rowsets.length; i++){
if(rowsets[i].getAttribute("name") == "skillqueue"){
skillrows = rowsets[i].getElementsByTagName("row");
}
}
//Defines Table Headers
$("#tableskillqueuelist").append(
"<thead>" +
"<tr>" +
"<th>Order: </th> "+
"<th>Skill Name: </th> "+
"<th>Training to: </th> "+
"<th>Starts:</th> "+
"<th>Ends:</th> "+
"</tr> "+
"</thead>"+
"<tbody>"
);
for(var i = 0; i < skillrows.length; i++){
(function(i, skillrows) {
$.get("../getitemname", {itemid:skillrows.getAttribute("typeID")},function(itemname){
$("#tableskillqueuelist").append(
"<tr> " +
"<td>" + skillrows.getAttribute("queuePosition") + ". " +
"<td>" + itemname + "</td>" +
"<td>" + "|Train to: " + skillrows.getAttribute("level") + "</td>" +
"<td>" + "|Training Starts: " + skillrows.getAttribute("startTime") + "</td>" +
"<td>" + "|Training Ends: " + skillrows.getAttribute("endTime") + "<td>" +
"</tr>"
);
})
})(i, skillrows[i]);
}
//Ends the table body
$("#tableskillqueuelist").append("</tbody>");
});
});
Now i'm wondering what i need to do to have it successfully run the $("#tableskillqueuelist").tablesorter(); method. Since it seems like whenever i try and run it, the #tableskillqueuelist seems to be empty.
You need to tell table sorter that you've changed the data and that you want to sort it by triggering events.
Example from the docs: http://tablesorter.com/docs/example-ajax.html
$("table").tablesorter();
$("#ajax-append").click(function() {
$.get("assets/ajax-content.html", function(html) {
// append the "ajax'd" data to the table body
$("table tbody").append(html);
// let the plugin know that we made a update
$("table").trigger("update");
// set sorting column and direction, this will sort on the first and third column
var sorting = [[2,1],[0,0]];
// sort on the first column
$("table").trigger("sorton",[sorting]);
});
return false;
});
HTH

how to store array data in table?

I wanted the user to enter any alphabet in a text field, when he/she clicks on the Find! button, it will go through my php file and find a list of words that start with that alphabet (of course it's only a limited amount of words). And I want to output it to a table, with 5 columns, each cell containing one word.
Something like this:
in my HTML:
<label>
Enter any alphabet:
<input name="alphabet" type="text" id="alphabet"></label>
<input type="button" value="Find!" id="goFind">
<table border="1" id="output">
</table>
and Javascript:
$(document).ready(function () {
$.ajaxSetup({
cache: false
});
var bunchOfWords = function (data) {
var listOfWords = "";
if(!Array.isArray(data)) {
return false;
}
else {
for(i = 0; i < data.length; i = +5) {
listOfWords += "<tr><td>" + data[i] + "</td>" +
"<td>" + data[i] + "</td>" +
"<td>" + data[i] + "</td>" +
"<td>" + data[i] + "</td>" +
"<td>" + data[i] + "</td></tr>";
}
}
};
$("#goFind").click(function () {
var theWord = $("#alphabet").val();
$("#output").html("Loading..."); //gives the user an indication that it's loading
$.getJSON("wordslookup.php", "startswith=" + theWord, listOfWords);
});
});
Can't seem to figure out what's wrong.
listOfWords is out of scope in $.getJSON also its not a function, you should pass bunchOfWords to $.getJSON instead. To put the data in the table simply replace the current inner html, $("#output").html(listOfWords);

Refresh table after using jQuery .append()

The following code gets a JSON object and then spits its contents out into a <table>. The first time I do it I get my JSON content just fine. However, when I refresh, the refreshed data is stuck onto the bottom of my table. How do I refresh the data to show the new data only? I tried using .remove() but there was an obvious deleting and then a refresh of data.
$(function() {
$('#ReportedIssue').change(function() {
//$('.data').remove()
$.getJSON('/CurReport/GetUpdatedTableResults', function(json) {
for (var i = 0; i < json.GetDocumentResults.length; i++) {
$('#DocumentInfoTable').append(
"<tr class='data'>" +
"<td>" + json.GetDocumentResults[i].Document.DocumentId + "</td>" +
"<td>" + json.GetDocumentResults[i].Document.LanguageCode + "</td>" +
"<td>" + json.GetDocumentResults[i].ReportedIssue + "</td>" +
"<td>" + json.GetDocumentResults[i].PageNumber + "</td>" +
"</tr>"
);
};
});
});
});
Thank you,
Aaron
It will be more efficient to build the HTML as follows (and of course, solves the problem you're experiencing):
$(function() {
$('#ReportedIssue').change(function() {
//$('.data').remove()
$.getJSON('/CurReport/GetUpdatedTableResults', function(json) {
var str = '';
for (var i = 0; i < json.GetDocumentResults.length; i++) {
str += "<tr class='data'>" +
"<td>" + json.GetDocumentResults[i].Document.DocumentId + "</td>" +
"<td>" + json.GetDocumentResults[i].Document.LanguageCode + "</td>" +
"<td>" + json.GetDocumentResults[i].ReportedIssue + "</td>" +
"<td>" + json.GetDocumentResults[i].PageNumber + "</td>" +
"</tr>"
};
$('#DocumentInfoTable').html(str);
});
});
});

Categories

Resources