How to implement pagination in dynamic html table - javascript

I am having a html table which is being dynamically populated via JSON data. I have to implement pagination to this table in order to show only 10 records per page.
I have tried Datatable.js and smpSortaableTable.js which shows the option for previous and next button but all the records are shown on first page only.
Libraries:
<link rel="stylesheet" href="smpSortableTable.css">
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"
integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo"
crossorigin="anonymous"></script>
<script src="smpSortableTable.js"></script>
Table design is:
<div class="card-body">
<table class="table table-bordered table-hover order-list table-responsive-sm table-responsive-md table-striped" style="font-size:small;" id="Open_table">
<thead class="thead-dark">
<tr>
<th>TAF-No</th>
<th>Purpose</th>
<th>Travel Location</th>
<th>No of Days</th>
<th>Advance</th>
<th>Remarks</th>
<th></th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
Javascript code:
<script>
var name1 = "<%= Request.Cookies["emailid"].Value.ToString() %>";
//alert(name1);
var dtt = document.getElementById("year_date").value;
//alert(dtt);
var tafid;
if (document.getElementById("open_taf").value == "") {
tafid = 0;
var myObj;
var request = new XMLHttpRequest();
request.overrideMimeType("application/json");
request.open("GET", "API");
request.send();
request.onload = function () {
var superHero = request.response;
myObj = JSON.parse(superHero);
myObj = JSON.parse(myObj);
//var counter = myObj.count;
for (i in myObj.open_list) {
check3(i, myObj.open_list[i].taf_no, myObj.open_list[i].purpose, myObj.open_list[i].loc_of_vst, myObj.open_list[i].no_of_days, myObj.open_list[i].adv_amt, myObj.open_list[i].remarks, myObj.open_list[i].tid, name1);
}
}
}
else {
tafid = document.getElementById("open_taf").value;
var myObj;
var request = new XMLHttpRequest();
request.overrideMimeType("application/json");
request.open("GET", "API");
request.send();
request.onload = function () {
var superHero = request.response;
myObj = JSON.parse(superHero);
myObj = JSON.parse(myObj);
//var counter = myObj.count;
//alert(counter);
for (i in myObj.open_list) {
check3(i, myObj.open_list[i].taf_no, myObj.open_list[i].purpose, myObj.open_list[i].loc_of_vst, myObj.open_list[i].no_of_days, myObj.open_list[i].adv_amt, myObj.open_list[i].remarks, myObj.open_list[i].tid, name1);
}
}
}
}
function check3(counter, data, data1, data2, data3, data4, data5, data6, data7, data8) {
//alert('2');
var newRow = $("<tr>");
var cols = "";
cols += '<td name="name' + counter + '">' + data + '</td>';
cols += '<td name="from_loc' + counter + '">' + data1 + '</td>';
cols += '<td name="to_loc' + counter + '">' + data2 + '</td>';
cols += '<td name="date_of_travel' + counter + '">' + data3 + '</td>';
cols += '<td name="status' + counter + '">' + data4 + '</td>';
cols += '<td name="status' + counter + '">' + data5 + '</td>';
cols += '<td>Details</td>';
newRow.append(cols);
$("table.order-list").append(newRow);
$('#Open_table').smpSortableTable(check3,5);
}
</script>
Expected result is page numbers and previous and next button at the bottom. Please guide and thank you in advance for your help.

After including the Datatable.js in your file. You need to apply that DataTable on your table in ready() function. Try this..
$(document).ready( function () {
$('#Open_table').DataTable();
} );

Related

adding click event on Html table rows

I have an Html table and I'm feeding that table with data from firebase so in my Html there's no table data td i have tried to add on click on the table row tr but this is adding the click on the table header th
<div>
<table>
<tr onclick="myFunction(this)">
<th>Name</th>
<th>Phone</th>
<th>ID</th>
</tr>
<tbody id="table">
</tbody>
</table>
</div>
<script>
function myFunction(x) {
alert("Row index is: " + x.rowIndex);
}
</script>
the second try is js I have tried this and many other functions like this one but it did nothing no response no errors
function addRowHandlers() {
var table = document.getElementById("table");
var rows = table.getElementsByTagName("tr");
for (i = 1; i < rows.length; i++) {
var row = table.rows[i];
row.onclick = function(myrow){
return function() {
var cell = myrow.getElementsByTagName("td")[0];
var id = cell.innerHTML;
alert("id:" + id);
};
}(row);
}
}
and this is how im feeding td from firebase
var ref = firebase.database().ref("users");
ref.on("value", function(data){
$('#table').empty()
var content = '';
data.forEach(function(childSnapshot){
if (childSnapshot.exists()){
var childData = childSnapshot.val();
console.log(childData);
content +='<tr>';
content += '<td>' + childData.username + '</td>';
content += '<td>' + childData.phone + '</td>';
content += '<td>' + childSnapshot.key + '</td>';
content += '</tr>';
};
});
$('#table').append(content);
});
how to add onClick event to each row I'm new to HTML and js languages
You can refactor your function like
var ref = firebase.database().ref("users");
ref.on("value", function (data) {
$('#table').empty()
data.forEach(function (childSnapshot) {
if (childSnapshot.exists()) {
var childData = childSnapshot.val();
console.log(childData);
const tr = document.createElement('tr')
let content = ""
content += '<td>' + childData.username + '</td>';
content += '<td>' + childData.phone + '</td>';
content += '<td>' + childSnapshot.key + '</td>';
tr.innerHTML = content;
tr.onclick = function () {
alert('tr', childData.phone)
}
$('#table tbody').append(tr);
};
});
});

How to display all the data from table?

1.This is my code for my HTML table where I'm unable to display the data from it using my javascript code below.
<table id="empTable">
<tr>
<th>Type</th>
<th>SimiScore</th>
<th>Rank</th>
<th>Introversion/Extraversion</th>
<th>Intuitive/Observant</th>
<th>Thinking/Feeling</th>
<th>Judging/Perceiving</th>
</tr>
{% for doc in docs %}
<tr>
<td>{{doc["type"]}}</td>
<td>{{doc["Simiscore"]}}</td>
<td>{{doc["Rank"]}}</td>
<td>{{doc["Introversion/Extraversion"]}}</td>
<td>{{doc["Intuitive/Observant"]}}</td>
<td>{{doc["Thinking/Feeling"]}}</td>
<td>{{doc["Judging/Perceiving"]}}</td>
</tr>
{% endfor %}
</table>
<p><input type="button" id="bt" value="Show Table Data" onclick="showTableData()" /></p>
<p id="info"></p>
2.This is my javascript code to display the data, but I'm unable to display it
<script>
function showTableData() {
document.getElementById('info').innerHTML = "";
var myTab = document.getElementById('empTable');
// LOOP THROUGH EACH ROW OF THE TABLE AFTER HEADER.
for (i = 1; i < myTab.rows.length; i++) {
// GET THE CELLS COLLECTION OF THE CURRENT ROW.
var objCells = myTab.rows.item(i).cells;
// LOOP THROUGH EACH CELL OF THE CURENT ROW TO READ CELL VALUES.
for (var j = 0; j < objCells.length; j++) {
info.innerHTML = info.innerHTML + ' ' + objCells.item(j).innerHTML;
}
info.innerHTML = info.innerHTML + '<br />'; // ADD A BREAK (TAG).
}
}
</script>
{
$(document).ready(function()
{
$.ajax({
url: "getjson.php",
type: "POST",
dataType:"json",
success: function (response)
{
var trHTML = '';
$.each(response, function (key,value) {
trHTML +=
'<tr><td>' + value.id +
'</td><td>' + value.konu +
'</td><td>' + value.aciklama +
'</td><td>' + value.giris_tarih +
'</td><td>' + value.degistirilme_tarih +
'</td><td>' + value.ad_soyad +
'</td><td>' + value.email +
'</td></tr>';
});
$('#records_table').append(trHTML);
}
});
});
}
this is an example you can use

How to append table>tr in table>tbody(already existing table) in javascript(working with Chrome extension)

I am working with chrome extension .My main problem is I am not
able to append my tr under tbody as the error occur and stating
"Cannot read property 'getElementsByTagName' of null". So how Do I
append this in chrome extension using javascript.
In background.js I have tried this:
response.json().then(function (data) {
var dResponse = data.results;
if (dResponse.length > 0) {
var tableRef = document.getElementsByTagName('tbody')[0];
for (var obj = 0; obj < dResponse.length; obj++) {
var result = '<tr>' +
'<td>' + dResponse[obj].title + '</td>' +
'<td>' + dResponse[obj].category_path + '</td>' +
'<td>' + dResponse[obj].price + '</td>' +
'<td>' + dResponse[obj].num_favorers + '</td>' +
'<td>' + dResponse[obj].tags + '</td>';
result += '</tr>';
var tableRef =
tableRef.appendChild(result);
console.log(result);
};
}
});
I am hitting API and and my response is under data.
When I console my result so as output tr is comming.
var tableRef = document.getElementById('myTable').getElementsByTagName('tbody')[0];
var tableRef = document.getElementsByTagName('tbody')[0];
both lines are giving this "Cannot read property 'getElementsByTagName' error
I also tried other ways to append but everytime it gives same error.I am not getting why this is happening.
response.json().then(function (data) {
var dResponse = data.results;
if (dResponse.length > 0) {
var tableRef = document.getElementsByTagName('tbody')[0];
for (var obj = 0; obj < dResponse.length; obj++) {
var result = '<tr>' +
'<td>' + dResponse[obj].title + '</td>' +
'<td>' + dResponse[obj].category_path + '</td>' +
'<td>' + dResponse[obj].price + '</td>' +
'<td>' + dResponse[obj].num_favorers + '</td>' +
'<td>' + dResponse[obj].tags + '</td>';
result += '</tr>';
var tableRef =
tableRef.appendChild(result);
console.log(result);
};
}
});
```
```background.html```
<div class="table-responsive mb-0" data-toggle="lists">
<table class="table table-sm table-nowrap card-table" id="myTable">
<thead>
<tr>
<th>Product Name</th>
<th>Category</th>
<th>Price</th>
<th>Favourites</th>
<th>Tags</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
```
<script src="background.js"></script>
> I am getting error "Cannot read property 'getElementsByTagName' of null". I only want to append my tr under tbody
I think that your background.js executes before the page has loaded, You can't access the "tbody"
This is how to run background.js after page load.
<script>
function init(){
var tag = document.createElement("script");
tag.src = "background.js";
document.getElementsByTagName("head")[0].appendChild(tag);
}
</script>
<head></head>
<body onload='init()'>
<table><tbody><tbody></table>
</body>

Convert ISO 8601 date format

I get an ajax call response in which i get datetime in "2019-02-07T14:00:11.374+0530" format. I want to convert this as Feb-07-2019 14:00.
I try this as following but its showing current date, not ajax response date. How do i convert date coming from ajax response. I get datetime from ajax response by calling "starttime"
This my code
function format(driver_data) {
var a = '';
var b = '';
var i;
var ps = new Date();
ps = ps.toDateString() + " " + ps.getHours() + ":" + ps.getMinutes();
console.log(ps)
for (i = 0; i < driver_data.length; i++) {
a = '<table class="table table-striped table-bordered table-hover"style="padding-left:0px;">' + '<thead> <tr> <th>Trip Id</th> <th>Name</th> <th>Source</th> <th>Destination</th> <th>Date/Time</th> </tr> </thead>' + '<tbody>';
b = b + '<tr>' +
'<td>' + driver_data[i].d_tripid + '</td>' +
'<td>' + driver_data[i].employeename + '</td>' +
'<td>' + driver_data[i].srclocation + '</td>' +
'<td>' + driver_data[i].destlocation + '</td>' +
'<td>' ps'</td>' +
'</tr>';
}
var final = a + b + '</tbody></table>';
return final;
}

JS Append Row in HTML Table

I have a hidden field with some values, I have to append these values in HTML table.The number of columns in table is fixed.
I have appended successfully,but after first row,it should append data in new row,instead it is appending in the same row.
This is how I am doing
$("#btntbl").click(function () {
debugger
var tabl = $("#testTable");
var vals = $("#txthidden").val();
for (var i = 0; i < vals.split(";").length; i++) {
for (var j = 0; j < vals.split(";")[i].split(",").length; j++) {
tabl.append("<td>" + vals.split(";")[i].split(",")[j] + "</td>");
}
}
});
Also note that some users dont have value of disabled column
JS Fiddle
How can I add new row each time clicking the button?
You need to split twice and create tr for each row:
$("#btntbl").click(function () {
var tabl = $("#testTable"),
vals = $("#txthidden").val(),
rows = vals.split(';'),
columns, i;
for (i = 0; i < rows.length; i++) {
columns = rows[i].split(',');
tabl.append(
'<tr>' +
'<td>' + columns[0] + '</td>' +
'<td>' + columns[1] + '</td>' +
'<td>' + (columns[2] || '') + '</td>' +
'</tr>'
);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="button" id="btntbl" value="Export to table">
<input type="hidden" value="User1,pwd1;User2,pwd2,disabled;User3,pwd3,disabled;User4,pwd4" id="txthidden" />
<table id="testTable" border="2">
<thead valign="top">
<tr>
<th>User</th>
<th>Password</th>
<th>Disabled</th>
</tr>
</thead>
</table>
Just change target by adding a row
Change
var tabl = $("#testTable");
To
var tabl = $('<tr>');
$("#testTable").append( tab1);
Here is how you can do it
var convertToTable = function (val) {
val = val.split(';');
val = val.map(function (v) {
v = v.split(',');
if (v.length === 2) v[v.length] = 'NA';
return '<td>' + v.join('</td><td>') + '</td>';
});
val = '<tr>' + val.join('</tr><tr>') + '</tr>';
return val;
}
and then
tabl.html(convertToTable(vals));
Demo here
jsFiddle demo
$("#btntbl").click(function () {
var parts = $("#txthidden").val().split(";"), i=0;
for (;i<parts.length;) {
var j=0, tr="<tr>", subParts=parts[i++].split(",");
for (;j<3;) tr += "<td>" + (subParts[j++]||"") +"</td>"; // concatenate
$("#testTable").append( tr +"</tr>" ); // Append once
}
});
You forgot about TD tag, just use open tag before TD and close it in the end

Categories