How to empty the data inside tbody using jquery? - javascript

I want to empty the data inside tbody, I tried:
$("#detail_tbody").html("");
$("#detail_tbody").empty();
but the result is that the current page is cleared.
When i click the next page,the data will show again.How can i empty all of them?
<table id="detail_table">
<tr align="center">
<th style="display: none;"></th>
<th width="100px">1</th>
<th width="130px">2</th>
<th width="130px">3</th>
<th width="130px">4</th>
<th width="130px">5</th>
<th width="130px">6</th>
<th width="130px">7</th>
</tr>
<tbody id="detail_tbody"></tbody>
</table>
The js is :
for (var i = 0; i < productTradeDetail_list.length; i++) {
productTradeDetail_listobj = productTradeDetail_list[i];
p += "<tr align=\"center\">" +
"<td style='display: none;'>" + i + "</td>" + //
"<td>" + productTradeDetail_listobj.procode + "</td>" +
"<td>" + productTradeDetail_listobj.proname + i + "</td>" +
"<td>" + productTradeDetail_listobj.tradename + "</td>" +
"<td>" + productTradeDetail_listobj.confirmatm + "</td>" +
"<td>" + productTradeDetail_listobj.confirmvol + "</td>" +
"<td>" + productTradeDetail_listobj.statename + "</td>" +
"<td>" + productTradeDetail_listobj.tradedata + "</td></tr>";
}
$("#detail_tbody").empty();
$("#detail_tbody").append(p);
page = new Page(5, "detail_table", "detail_tbody");
$("#tradeDetail_pageLabel").val(page.pageIndex + 1 + "/" + page.pageCount);
ADD:I have two response,i need clear current data of response and show another when i change into next response.

Related

How to add a row in every 3 rows in table javascript

I create table with print out data from database like this:
here the JS and HTML.
JS
function initDataTableSaldoRek1() {
showLoadingCss()
$.ajax({
url: baseUrl + "api_dashboard/get_ivest",
dataType: 'JSON',
type: "GET",
success: function (res) {
var data = res.return;
$("#date").html(data[0].TANGGAL);
$('#table-invest tbody').empty();
$.each(data, function (key, val) {
var html = "<tr>" +
"<td>" + val.DATE + "</td>" +
"<td>" + val.TYPE + "</td>" +
"<td align='right'>" + accounting.formatNumber(val.USD,2,".",",") + "</td>" +
"<td align='right' >" + accounting.formatNumber(val.EUR,2,".",",") + "</td>" +
"</tr>";
$('#table-invest tbody').append(html);
});
hideLoadingCss()
},
});
}
HTML
<div class="view-table" >
<table id="table-invest" class="table table-bordered">
<thead>
<tr>
<th style="background-color: #67a2d8" width="12.5%">DATE</th>
<th style="background: #67a2d8" width="12.5%">TYPE OF PAYMENT</th>
<th style="background: #67a2d8" width="12.5%">EUR</th>
<th style="background: #67a2d8" width="12.5%">USD</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
and i want add a row every 3 rows that sum column 2 & 3 as below .
Everybody in here have ever experience to create table as below before in JavaScript?
Thank you..
Just make a check on each third row, since the $.each callback provides an index value.
function initDataTableSaldoRek1() {
showLoadingCss()
$.ajax({
url: baseUrl + "api_dashboard/get_ivest",
dataType: 'JSON',
type: "GET",
success: function (res) {
var data = res.return;
$("#date").html(data[0].TANGGAL);
let html = "<tr>" +
"<td>" + val.DATE + "</td>" +
"<td>" + val.TYPE + "</td>" +
"<td align='right'>" + accounting.formatNumber(val.USD, 2, ".", ",") + "</td>" +
"<td align='right' >" + accounting.formatNumber(val.EUR, 2, ".", ",") + "</td>" +
"</tr>";
$('#table-invest tbody').append(html);
$('#table-invest tbody').empty();
$.each(data, function (key, val) {
if ((key+1) % 3 === 0 ){
html = `<tr><td>TOTAL</td></tr> ${html}`;
}else{
return html;
}
});
hideLoadingCss()
},
});
}
You can simply use a counter, when this counter reaches the amount of rows you want, add the "total" row and reset the counter.
Also, keep track of the total value (I don't know which total you want to calculate, so it is up to you this part), inside the if to check the counter, reset this total too.
Something like this:
let counter = 0;
let sumTotal = 0;
$.each(data, function(key, val) {
var html = "<tr>" +
"<td>" + val.DATE + "</td>" +
"<td>" + val.TYPE + "</td>" +
"<td align='right'>" + accounting.formatNumber(val.USD, 2, ".", ",") + "</td>" +
"<td align='right' >" + accounting.formatNumber(val.EUR, 2, ".", ",") + "</td>" +
"</tr>";
sumTotal = 0;//USE YOUR LOGIC TO CALCULATE AND INCREASE TOTAL
$('#table-invest tbody').append(html);
counter++;
//check if it is the moment to add the new row total
if (counter == 3){
let newRow = "<tr>" +
"<td>Total: " + sumTotal + "</td>" +
"</tr>";
$('#table-invest tbody').append(newRow);
counter = 0;
sumTotal = 0;
}
});

Adding images to HTML table cell via JavaScript

I'm just trying to do this but I keep getting only countries[i].Code instead of the image, can anyone help me out with this ?
function flist(){
var list = document.querySelector("#flist");
var myRows = "";
for(var i=0; i < countries.length; i++){
myRows += "<tr>" +
"<td>" + "<figure>" + "<img src=" + "\"" + "/flags/"+ countries[i].Code +
".png" + "\"" + "alt=" + "\"" + countries[i].Code + "\"" + "height=" +"\""+ "14"+ "\"" + " width=" + "\"" +"14" + "\""+ ">" +"</figure>" + "</td>" +
"<td>" + countries[i].Code + "</td>" +
"<td>" + countries[i].Name.English + "</td>" +
"<td>" + countries[i].Continent + "</td>" +
"<td>" + countries[i].AreaInKm2.toString()+ "</td>" +
"<td>" + countries[i].Population.toString() + "</td>" +
"<td>" + countries[i].Capital + "</td>" +
"</tr>";
}
list.innerHTML += myRows;
};
Example of Countires
var countries = [
{
Code: "AF",
Continent: "Asia",
AreaInKm2: 652230,
Population: 35530081,
Capital: "Kabul",
Name: {
"English": "Afghanistan",
"Arabic": "أفغانستان",
"Chinese": "阿富汗",
"Franch": "Afghanistan",
"Hindi": "अफ़ग़ानिस्तान",
"Korean": "아프가니스탄",
"Japanese": "アフガニスタン",
"Russian": "Афганистан"
}
Im trying to make a table in the HTML of each county and in the begging to have a flag
<h4 id="subtitle">List of Countries and Dependencies</h4>
<table id="outputTable">
<thead>
<tr>
<th>Flag</th>
<th>Code</th>
<th id="countyrName">Country/Dep. Name</th>
<th>Continent</th>
<th>Area (Km<sup>2</sup>)</th>
<th>Population</th>
<th>Capital</th>
</tr>
</thead>
<tbody id="flist"></tbody>
</table>
If you use singles quotes for dealing with building HTML in javascript, you don't have to escape the double quotes around params and is less prone to making mistakes.
myRows += '<tr>' +
'<td><figure><img src="/flags/' + countries[i].Code + '.png" alt="' + countries[i].Code + '" height="14" width="14" /></figure></td>' +
'<td>' + countries[i].Code + '</td>' +
'<td>' + countries[i].Name.English + '</td>' +
'<td>' + countries[i].Continent + '</td>' +
'<td>' + countries[i].AreaInKm2.toString()+ '</td>' +
'<td>' + countries[i].Population.toString() + '</td>' +
'<td>' + countries[i].Capital + '</td>' +
'</tr>';
I'd be keeping your HTML as HTML, keep it out of the JavaScript. If you change from a table to ul you now have to go rewrite your javascript.
Set a hidden template. Make a copy of the template to work with and remove the template all together. Then you can clone the template an replace values as needed without needing to worry about your HTML structure.
var countries = [{
Code: "AF",
Continent: "Asia",
AreaInKm2: 652230,
Population: 35530081,
Capital: "Kabul",
Name: {
"English": "Afghanistan",
"Arabic": "أفغانستان",
"Chinese": "阿富汗",
"Franch": "Afghanistan",
"Hindi": "अफ़ग़ानिस्तान",
"Korean": "아프가니스탄",
"Japanese": "アフガニスタン",
"Russian": "Афганистан"
}}]
//Make a clone out of tempate
var template = document.getElementById("rowTemplate").cloneNode(true);
template.removeAttribute("id")
console.log(template);
//get rid of original we done't need it any more
document.getElementById("flist").innerHTML = "";
function flist() {
var list = document.querySelector("#flist");
var myRows = "";
for (var i = 0; i < countries.length; i++) {
//make a working copy of the template
var workingTemplate = template.cloneNode(true);
//Do the replace
workingTemplate.innerHTML = workingTemplate.innerHTML
.replace(/{{code}}/g, countries[i].Code)
.replace(/{{name}}/g, countries[i].Name.English)
.replace(/{{continent}}/g, countries[i].Continent)
.replace(/{{area}}/g, countries[i].AreaInKm2)
.replace(/{{population}}/g, countries[i].Population)
.replace(/{{capital}}/g, countries[i].Capital);
myRows += workingTemplate.outerHTML;
}
//update the table
list.innerHTML += myRows;
};
flist();
#rowTemplate {
display: none;
}
<h4 id="subtitle">List of Countries and Dependencies</h4>
<table id="outputTable">
<thead>
<tr>
<th>Flag</th>
<th>Code</th>
<th id="countyrName">Country/Dep. Name</th>
<th>Continent</th>
<th>Area (Km<sup>2</sup>)</th>
<th>Population</th>
<th>Capital</th>
</tr>
</thead>
<tbody id="flist">
<tr id="rowTemplate">
<td class="img">
<figure><img src="/flags/{{code}}" alt="{{code}}" height="14" width="14"></figure>
</td>
<td>{{code}}</td>
<td>{{name}}</td>
<td>{{continent}}</td>
<td>{{area}}</td>
<td>{{population}}</td>
<td>{{capital}}</td>
</tr>
</tbody>
</table>

JSON Formatting Issue?

I am trying to populate an html table of JSON data. I was provided the JSON data and cannot determine why it isn't populating but suspect the JSON may not be formatted properly. When I use other sample data it works, then when I sub in the JSON I was provided it doesn't work. I've tried copying the JSON into a file on my direct server, linking to what I was provided (here: https://boiling-fortress-75456.herokuapp.com/) and inserting it on myjson.com and reformatting the JSON data.
Here is my code:
<script>
$(function() {
var entries = [];
var dmJSON = "https://api.myjson.com/bins/6sjud?callback=?";
$.getJSON(dmJSON, function(data) {
$.each(data.entries, function(i, f) {
var tblRow = "<tr>" + "<td>" + f.rank + "</td>" + "<td>" + f.name + "</td>" + "<td>" + f.march_rank + "</td>" + "<td> " + f.april_rank + "</td>" + "<td>" + f.may_rank + "</td>" + f.personal_volume + "</td>" + f.team_volume + "</td>" + "</tr>"
$(tblRow).appendTo("#incentive tbody");
});
});
});
</script>
<div class="wrapper">
<div class="profile">
<table id= "incentive" border="1">
<thead>
<th>Rank</th>
<th>Name</th>
<th>March</th>
<th>April</th>
<th>May</th>
<th>Highest Rank</th>
<th>Personal Volume</th>
<th>Team Volume</th>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
You need to get the objects from affiliate
$.each(data.affiliate, function(i, f) {
var tblRow = "<tr>" + "<td>" + f.rank + "</td>" + "<td>" + f.name + "</td>" + "<td>" + f.march_rank + "</td>" + "<td> " + f.april_rank + "</td>" + "<td>" + f.may_rank + "</td>" + f.personal_volume + "</td>" + f.team_volume + "</td>" + "</tr>"
$(tblRow).appendTo("#incentive tbody");
});
Response from service
{
"affiliate":[{
"rank":1,"name":"Sally","march_rank":"Gold","april_rank":"Silver","may_rank":"Silver","highest_rank":"Silver","team_volume":12345
},{
"rank":2,"name":"Zelda","march_rank":"Gold","april_rank":"Bronze","may_rank":"Silver","highest_rank":"Gold","team_volume":12345
}
]
}

Firebase child_changed for tables

When using child_added to populate a table, I use append() to show the data on the HTML table, but how do I do it with child_changed? Should I delete the row and then append a new one with the changed information? If so, how do I delete this row? Or maybe use something else instead of append() to update the data on the HTML table?
HTML Table
<table id="tableAssets" class="mdl-data-table mdl-js-data-table mdl-shadow--2dp">
<thead>
<tr id="tableHeader">
<th class="mdl-data-table__cell--non-numeric">Name</th>
<th class="mdl-data-table__cell--non-numeric">Brand</th>
<th class="mdl-data-table__cell--non-numeric"> </th>
</tr>
</thead>
<tbody id="table_body"> </tbody>
</table>
JavaScript
rootRef.on("child_added", snap => {
var assetKey = snap.child("id").val();
var name = snap.child("name").val();
var brand = snap.child("brand").val();
$("#table_body").append("<tr data-id='"+assetKey+"'>"+
"<td class='mdl-data-table__cell--non-numeric'>" + name + "</td>" +
"<td class='mdl-data-table__cell--non-numeric'>" + brand + "</td>" +
"<td class='mdl-data-table__cell--non-numeric'><div buttons>"+
"<button class='delete-btn'><i class='material-icons'>delete</i></button>"+" "+
"</div></td></tr>");
});
For child added use id in tr
rootRef.on("child_added", snap => {
var assetKey = snap.child("id").val();
var name = snap.child("name").val();
var brand = snap.child("brand").val();
$("#table_body").append("<tr id='row"+assetKey+"'>"+
"<td class='mdl-data-table__cell--non-numeric'>" + name + "</td>" +
"<td class='mdl-data-table__cell--non-numeric'>" + brand + "</td>" +
"<td class='mdl-data-table__cell--non-numeric'><div buttons>"+
"<button class='delete-btn'><i class='material-icons'>delete</i></button>"+" "+
"</div></td></tr>");
});
For Child Changed
rootRef.on("child_changed", snap => {
var assetKey = snap.child("id").val();
var name = snap.child("name").val();
var brand = snap.child("brand").val();
editrow = "row"+assetKey;
document.getElementById("editrow").innerHTML = "<td class='mdl-data-table__cell--non-numeric'>" + name + "</td>" +
"<td class='mdl-data-table__cell--non-numeric'>" + brand + "</td>" +
"<td class='mdl-data-table__cell--non-numeric'><div buttons>"+
"<button class='delete-btn'><i class='material-icons'>delete</i></button>"+" "+
"</div></td>");
});
This will help.

Imitate mouse click

I need to imitate mouse click on "Name" td after table draws, so it looks like sorting by name is default.
var link = "https://jsonplaceholder.typicode.com/users";
var usersData = [];
$(".buttonLoad").click(function () {
$(".buttonLoad").remove();
$.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>" )
}
});
$("table").removeClass("hide");
$('th.sort').click(function(){
var table = $(this).parents('table').eq(0)
var rows = table.find('tr:gt(0)').toArray().sort(comparer($(this).index()))
this.asc = !this.asc;
if (!this.asc){rows = rows.reverse()}
for (var i = 0; i < rows.length; i++){table.append(rows[i])}
})
function comparer(index) {
return function(a, b) {
var valA = getCellValue(a, index), valB = getCellValue(b, index)
return $.isNumeric(valA) && $.isNumeric(valB) ? valA - valB : valA.localeCompare(valB)
}
}
function getCellValue(row, index){ return $(row).children('td').eq(index).html() }
});
.hide{
display: none;
}
button{
margin: 3px;
}
table {
width: 100%;
margin: auto;
margin: 3px;
}
table th {
font-weight: bold;
}
table th, table td {
padding: 3px;
border: 1px solid #000;
}
thead th{
font: bold italic 100% sans-serif;
background-color: #f7e1b5;
}
.sort{
cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<button class="buttonLoad">Load data</button>
<table id="users" border="1" class="hide">
<thead>
<tr>
<th>ID</th>
<th class="sort" id="defaultSort">Name</th>
<th class="sort">Username</th>
<th class="sort">Email</th>
<th class="sort">Street</th>
<th>Suite</th>
<th>City</th>
<th>Zipcode</th>
<th>Geo</th>
<th>Phone</th>
<th>Website</th>
<th class="sort">CompanyName</th>
<th>CatchPhrase</th>
<th>bs</th>
</tr>
</thead>
</table>
Things like .trigger("click") or element.click() don't work at all.
Calls to methods like click or trigger should be made after your dom elements are ready for the purpose of the scenario that you want to achieve.
if your case, you were trying to sort them before the elements are fully loaded into the page, so whatever solution that you will be trying, it will simply not work cause that 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, it's described down below :)
this is my approach to get it working:
1- I've marked the default th that you need to initially sort by with an additional class (named default)
2- I've then added a call to simulate the click action after the data is loaded (using a selector with the default class into account)
// finished loading, now sort by name
$(".sort.default").click();
and here is a link to the complete working fiddle: https://jsfiddle.net/hakeero/rfeh0q7v/1/
You should create a function sort(th) that you can call from anywhere so that you don't need to bother imitating click or hacks like that.
1.extract the sort statements from $('th.sort').click(), and put them in a function defined as follows:
function sort(th) {
var table = $(th).parents('table').eq(0)
var rows = table.find('tr:gt(0)').toArray().sort(comparer($(th).index()))
th.asc = !th.asc;
if (!th.asc){rows = rows.reverse()}
for (var i = 0; i < rows.length; i++){table.append(rows[i])}
}
2.sorting by name
$.getJSON(link, function (data) {
...
// sorting by name as the default action
sort($("#defaultSort"));
});
3.change $('th.sort').click() accordingly.
$('th.sort').click(function(){
sort(this);
})
for your convenience, live demo click here
Since you aren't using click event, you can just move the function away form the .click()
function clickHandler(){...}
.click(clickHandler)
then you can just call clickHandler() if you want that action

Categories

Resources