Append data to datatable using Firebase - javascript

The table displays 'No data available' but the data was appended inside the table
TableImage[1]
this is my firebaseimage
here's my html code:
<div class="box box-success">
<div class="box-header">
<h3> Sales </h3>
<table id="orders" class="table table-bordered table-striped">
<thead>
<tr>
<th>ID</th>
<th>Product</th>
<th>Price</th>
<th>Quantity</th>
<th>Date Ordered</th>
<th>Date Delivered</th>
<th>Status</th>
</tr>
</thead>
<tbody id="example">
</tbody>
</table>
</div>
</div>
my javascript code:
$('#orders').dataTable();
var rootRef = firebase.database().ref().child("sales/");
rootRef.on("child_added", snap => {
var key = snap.key;
var product = snap.child("product").val();
var price = snap.child("price").val();
var quantity = snap.child("quantity").val();
var date_ordered = snap.child("date_ordered").val();
var date_delivered = snap.child("date_delivered").val();
$("#example").append("<tr id='" + key + "'><td>" + key + "</td><td>" +
product + "</td><td>" + price + "</td><td>" + quantity + "</td><td>" +
date_ordered + "</td><td>" + date_delivered + "</td><td>" +
"<a href = 'product_list.html' > View < /a></td > < /tr>");
});
can anyone help me? please .. :(

I have a small improvement for your code, you can check it out below. I think you should try to make it works with raw HTML table first before using dataTable plugin. I don't know which dataTable plugin you're using but maybe you got 'No data available' because at the time you init the plugin, your table is empty.
var rootRef = firebase.database().ref().child("sales/");
rootRef.on("child_added", snap => {
var row = snap.val();
var key = snap.key;
var product = row.product;
var price = row.price;
var quantity = row.quantity;
var date_ordered = row.date_ordered;
var date_delivered = row.date_delivered;
$("#example").append("<tr id='" + key + "'><td>" + key + "</td><td>" +
product + "</td><td>" + price + "</td><td>" + quantity + "</td><td>" +
date_ordered + "</td><td>" + date_delivered + "</td><td>" +
"<a href = 'product_list.html' > View < /a></td > < /tr>");
});

Related

is there a way to get the value from the first cell in html table row using javascript only?

I'm trying to figure out how to get the value from the first column of selected row inside the HTML table
i'm selecting the row using button created using this js code :
let tr = document.querySelectorAll("table tbody tr");
Array.from(tr).forEach(function (trArray) {
let button = document.createElement("i");
let td = document.createElement("td");
button.innerText = "";
button.className = "fa fa-eye";
button.style.color = "black";
button.hidden = "hidden";
button.onmouseover = "this.style.cursor='pointer'";
button.onclick = "viewrow(this)";
button.setAttribute("onclick", "viewrow(this)");
td.append(button);
trArray.append(td);
});
the table is created from code behind using stringbuilder
what I tried is this:
StringBuilder sb = new StringBuilder();
sb.Append("<table id=" + "contractstable" + " runat=" + "server" + " " + "class=" + "table" + " >");
sb.Append("<caption>البنود</caption>");
sb.Append("<thead>");
sb.Append("<tr>");
sb.Append("<th>رقم البند</th>");
sb.Append("<th>رقم الفاتورة</th>");
sb.Append("<th>صنف البند</th>");
sb.Append("<th>سعر القطعة</th>");
sb.Append("<th>القيمة</th>");
sb.Append("<th>الخصم</th>");
sb.Append("<th>المجموع</th>");
sb.Append("<th>حذف</th>");
sb.Append("</tr>");
sb.Append("</thead>");
sb.Append("<tbody id=" + "mytbody" + ">");
foreach (DataRow dr in dt.Rows)
{
sb.Append("<tr><td data-label=" + "رقم-البند" + ">" + dr["contract_id"]
+ "</td><td data-label= " + "رقم-الفاتورة" + " > " + dr["bill_id"]
+ "</td><td data-label=" + "صنف-البند" + ">" + dr["contract_category"]
+ "</td><td data-label=" + "سعر-القطعة" + ">" + dr["item_price"]
+ "</td><td data-label=" + "القيمة" + ">" + dr["amount"]
+ "</td><td data-label=" + "الخصم" + ">" + dr["discount"]
+ "</td><td data-label=" + "المجموع" + ">" + dr["total"] + "</td></tr>");
}
sb.Append("</tbody>");
sb.Append("</table>");
ltrTable.Text = sb.ToString();
then i want to get the selected row id , what i have tried :
function deleterow(element) {
var mytbody = document.getElementById("mytbody");
var firstchild = mytbody.querySelector("td");
var allName = firstchild.innerText;
var hiddentext2 = document.getElementById("myrow_id");
hiddentext2.focus();
hiddentext2.value = allName;
hiddentext2.blur();
}
You can use querySelector to get the first element. If it has more than one of similar elements, it always gets the first one.
Your cell does not have value either. You should use innerText instead.
function getrowid(element) {
var mytbody = document.getElementById("mytbody");
var firstchild = mytbody.querySelector("td");
var allName = firstchild.innerText;
console.log(allName)
}
getrowid()
<table>
<tbody id="mytbody">
<tr>
<td>First</td>
<td>Second</td>
</tr>
<tr>
<td>Third</td>
<td>Fourth</td>
</tr>
</tbody>
</table>
const tbody = document.querySelector("#myTbale > tbody");
const tds = tbody.querySelectorAll("td");
let tdVal = [];
tds.forEach(td => {
tdVal.push(td.innerText);
})
console.dir(tdVal[0]);
<table border="1" id="myTbale">
<thead>
<th>header 1</th>
<th>header 2</th>
</thead>
<tbody>
<tr>
<td>1st cell</td>
<td>1st cell</td>
</tr>
</tbody>
</table>

How to implement pagination in dynamic html table

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();
} );

Copying Checked rows from one table to another table

Actually i am looking to copy the checked rows from the table of one div (table 1) to table of another div(table 2). But with the below script, when i check more than one checkbox, the first checked row is replaced by the lastly checked row. But i want like each checked row of table 1 should come in table 2 as one by one.
Any help appreciated. Thanks in advance!!!
HTML
<div class="form-group" id="jqcc" >
<table id="order-table" name="order-table">
<tr>
<th>Select</th>
<th>Medication</th>
<th>Max Issue Limit</th>
</tr>
<tbody></tbody>
</table>
</div>
Javascript
<script>
var tableControl = document.getElementById('order-table');
$('#jqcc').click(function () {
var result = []
var x1;
var tab;
var count = document.querySelectorAll('input[type="checkbox"]:checked').length;
$('input:checkbox:checked', tableControl).each(function () {
result.push($(this).parent().next().text() + "," + "<br>"); // refers title of product
$(this).closest('tr').find('input').each(function () {
x1 = $(this).val(); // refers price of product
})
tab = "<tr><td>" + result + "</td>";
tab += "<td>" + x1 + "</td>";
tab += "<td>" + x1 + " </td>";
tab += "<td><button type='button' onclick='deletePerson(this);' class='btn btn-default'> <span class='glyphicon glyphicon-remove' /></button></td>";
tab += "</tr>";
tab += "</tbody>"
$("#charges").html("<table id='peopleTable' class='table table-bordered table-condensed table-striped'><thead><tr><th>Description</th><th>Actual Amount</th> <th>Claim Amount</th> <th></th></tr></thead>" + tab + "</table>").show();
});
});
</script>
You try to change:
<script>
var tableControl = document.getElementById('order-table');
$('#jqcc').click(function () {
var result = []
var x1;
var tab = "";
var count = document.querySelectorAll('input[type="checkbox"]:checked').length;
$("#charges").html("<table id='peopleTable' class='table table-bordered table-condensed table-striped'><thead><tr><th>Description</th><th>Actual Amount</th><th>Claim Amount</th> <th></th></tr></thead><tbody></tbody></table>").show();
$('input:checkbox:checked', tableControl).each(function () {
result.push($(this).parent().next().text() + "," + "<br>"); // refers title of product
$(this).closest('tr').find('input').each(function () {
x1 = $(this).val(); // refers price of product
//
tab = "<tr><td>" + result + "</td>";
tab += "<td>" + x1 + "</td>";
tab += "<td>" + x1 + " </td>";
tab += "<td><button type='button' onclick='deletePerson(this);' class='btn btn-default'> <span class='glyphicon glyphicon-remove' /></button></td>";
tab += "</tr>";
// append row html to table with id
$("#peopleTable").append(tab);
})
});
});

show json different field in html table

my code showing the image and title and summary for all json file entries all what i need to show the image , title and summary to the first entry only and will show title to other entries.
please advise.
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"> </script>
<script>
$(function() {
var entries = [];
var dmJSON = "http://localhost:8080/Newfolder/test.json";
$.getJSON( dmJSON, function(data) {
$.each(data.entries, function(i, f) {
var tblRow = "<tr>" + "<td>" + f.image + "</td>" + "<td>" + f.title + "</td>" + "<td>" + f.summary + "</td>" + "</tr>"
$(tblRow).appendTo("#entrydata tbody");
});
});
});
</script>
</head>
<body>
<div class="wrapper">
<div class="profile">
<table id= "entrydata" border="1">
<thead>
<th>ID</th>
<th>UserName</th>
<th>Message</th>
<th>Location</th>
<th>Time</th>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
</body>
</html>
Hard to understand what you're asking but I take it as you want First Name in the first table cell and first name and ID in the second.
var cutName = f.user.username.indexOf( ' ' ),
firstName = f.user.username.substr( 0, cutName == -1 ? 0 : cutName ),
tblRow = "<tr><td>" + firstName + "</td><td>" + firstName + " " + f.id + "</td><td>" + f.message + "</td><td> " + f.location + "</td><td>" + f.at + "</td></tr>";
Basically, use indexOf( ' ' ) to find the space after the first name. If the user only has one name (no space) then it returns -1 otherwise it is the index of the space. Then use substr to cut out the name.
Hope this helps. :)

On initial select change, jquery does not update/render html in the view

My view seems to be one step behind after a select change. I have a select/dropdown list that is populated with a getJSON request. After an initial selection, I verified in fiddler that the request was successful, but my view does not update. The crazy thing is that when I make another selection, thereafter, the view is then updated with the previous data, and continues on in this fashion. What am I missing?
Here is my HTML:
<div id="ClientSection">
<p>
#Html.Label("clientId", "Client")
#Html.DropDownListFor(x => x.PrimaryClient, Enumerable.Empty<SelectListItem>(),
"Choose Client", new {id = "clientId"})
</p>
<table id="clientLocationsTable">
<thead>
<tr>
<th>Region</th>
<th>Location</th>
<th>Address</th>
<th>Suite</th>
<th>City</th>
<th>State</th>
<th>Zip Code</th>
<th>Phone #</th>
<th>Email</th>
<th>Contact</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
And my JavaScript:
#section scripts
{
<script>
$(document).ready(function () {
// populate main client dropdown
$(function() {
$.getJSON("/api/client/getclients/", function(data) {
$.each(data, function (index, clientObj) {
$("#clientId").append(
$("<option/>").attr("value", clientObj.Id)
.text(clientObj.CompanyName)
);
});
});
});
// create new array
var otherClientLocations = new Array();
$("#clientId").change(function () {
// clear table body
$("#clientLocationsTable > tbody").empty();
// create new array
var clientList = new Array();
// set the id
var primaryId = $("#clientId").val();
$.getJSON("/api/client/getclientotherlocations/" + primaryId, function (data) {
// populate otherClientLocations Array
$.each(data, function(key, val) {
clientList.push(val);
});
otherClientLocations = clientList;
});
// create rows if needed
if(otherClientLocations.length > 0) {
$.each(otherClientLocations, function(key, val) {
$("#clientLocationsTable tbody")
.append("<tr><td>" + val.CompanyRegion +
"</td><td>" + val.CompanyLocationCode + "</td>"
+ "<td>" + val.CompanyAddress + "</td>" + "<td>" +
val.CompanySuite + "</td><td>" + val.CompanyCity +
"</td><td>" + val.CompanyState + "</td><td>" +
val.CompanyZipCode + "</td><td>" + val.CompanyPhoneNumber
+ "</td><td>" + val.CompanyEmail + "</td><td>" +
val.CompanyContactFn + " " + val.CompanyContactLn +
"</td>" + "</tr>");
});
}
});
});
</script>
}
You're not accounting for the fact that the json is being fetched asynchronously. You update the dom before the json has been returned from the server.
Try:
$(document).ready(function () {
// populate main client dropdown
$(function() {
$.getJSON("/api/client/getclients/", function(data) {
$.each(data, function (index, clientObj) {
$("#clientId").append(
$("<option/>").attr("value", clientObj.Id)
.text(clientObj.CompanyName)
);
});
});
});
// create new array
var otherClientLocations = new Array();
$("#clientId").change(function () {
// clear table body
$("#clientLocationsTable > tbody").empty();
// create new array
var clientList = new Array();
// set the id
var primaryId = $("#clientId").val();
$.getJSON("/api/client/getclientotherlocations/" + primaryId, function (data) {
// populate otherClientLocations Array
$.each(data, function(key, val) {
clientList.push(val);
});
otherClientLocations = clientList;
// create rows if needed (the section below has now been moved inside the callback
if(otherClientLocations.length > 0) {
$.each(otherClientLocations, function(key, val) {
$("#clientLocationsTable tbody")
.append("<tr><td>" + val.CompanyRegion +
"</td><td>" + val.CompanyLocationCode + "</td>"
+ "<td>" + val.CompanyAddress + "</td>" + "<td>" +
val.CompanySuite + "</td><td>" + val.CompanyCity +
"</td><td>" + val.CompanyState + "</td><td>" +
val.CompanyZipCode + "</td><td>" + val.CompanyPhoneNumber
+ "</td><td>" + val.CompanyEmail + "</td><td>" +
val.CompanyContactFn + " " + val.CompanyContactLn +
"</td>" + "</tr>");
});
}
});
});
});
Clarification: While the http request is underway, javascript execution continues concurrently. Your version went something like this:
$.getJSON("/api/client/getclientotherlocations/" + primaryId, function (data) {
// update array AFTER request is complete
});
// update dom based on value of array while request is still in progress
I've moved some brackets around so that now it is:
$.getJSON("/api/client/getclientotherlocations/" + primaryId, function (data) {
// update array AFTER request is complete
// then update dom based on new version of array
});

Categories