how to replace old table rows with new rows using javascript - javascript

I have created a dynamic table in html click here to view image the rows are created dynamically in javascript please refer the image click here to view image the data for table is fetched from firebase.
The problem I am facing is that the rows are getting added at the end of the table repeatedly resulting in duplicate rows please refer the image click here to view image how do I remove old rows and add new updated rows using javascript.

I have updated the snapshot.forEach loop with comments.
snapshot.forEach(function (data) {
var val = data.val();
var trow = document.createElement('tr');
var tdata = document.createElement('td');
var tdata1 = document.createElement('td');
tdata.innerHTML = val.Name;
tdata1.innerHTML = val.Votes;
trow.appendChild(tdata);
trow.appendChild(tdata1);
// set the Name as data-id attribute
// which can be used to query the existing row
tdata.setAttribute('data-id', val.Name);
// append the trow to tbdy
// only if there's no row with data-id value of val.Name
// otherwise update the vote column of the existing row
var existingRow = tbdy.querySelector('[data-id="' + val.Name + '"]');
if (!existingRow) {
tbdy.appendChild(trow);
} else {
existingRow.querySelectorAll("td")[1].innerHTML = val.Votes;
}
});

Related

Error "Cannot read property 'appendChild' of null at generateTable"

Can someone please shine some light on my this error is tossed? outputTable is properly referenced, and my JS file with the array countries is properly formatted.
I reckon I am appending erroneously, but I have tried all that I can.
PS if youre going to downvote, at least please tell me how to improve my questions in the future. I couldnt find a different question that exists already that matches my issue.
window.onload = generateTable();
function generateTable() {
// get the reference for the body
var outputTable = document.getElementById('outputTable');
// revoke existing Body element
if (outputTable) {
outputTable.removeChild(outputTable);
}
// creates a <tbody> element
var tableBody = document.createElement('tbody');
// creating all table rows
for (var i = 0; i < countries.length; i++) {
// creates a table row
var row = document.createElement('tr');
// create table column for flag
var colFlag = document.createElement('td');
//create image element in flag column
var flag = document.createElement('img');
flag.src = 'flags/' + countries[i].Code.toLowerCase() + '.png';
flag.alt = countries[i].Code;
row.appendChild(colFlag);
//append flag to flag column
colFlag.appendChild(flag);
// create table column for Code
var colCode = document.createElement('td');
//append code to code column
colCode.appendChild(document.createTextNode(countries[i].Code));
row.appendChild(colCode);
// create table column for country //**ENGLISH */
var colCountry = document.createElement('td');
colCountry.appendChild(document.createTextNode(countries[i].Name.English));
row.appendChild(colCountry);
// create table column for continent
var colCont = document.createElement('td');
colCont.appendChild(document.createTextNode(countries[i].Continent));
row.appendChild(colCont);
// create table column for area
var colArea = document.createElement('td');
colArea.appendChild(document.createTextNode(countries[i].AreaInKm2));
row.appendChild(colArea);
// create table column for population
var colPop = document.createElement('td');
colPop.appendChild(document.createTextNode(countries[i].Population));
row.appendChild(colPop);
// create table column for capital of country
var colCap = document.createElement('td');
colCap.appendChild(document.createTextNode(countries[i].Capital));
row.appendChild(colCap);
// attach columns to row
tableBody.appendChild(row);
outputTable.appendChild(tableBody);
}
// add the row to the end of the table body
document.body.appendChild(outputTable);
}

Reload HTML table after every AJAX call

My sequential AJAX calls keep appending rows to my HTML table, which I don't want. I want my table to be refreshed/reload on every call with new data, and not appended.
My Code:
var data = $('#data_input').val();
var tableRef = document.getElementById('data_table');
$.getJSON("/data/"+data, function(dataState)
{
// ...
for(var dataId in dataState)
{
var row = document.createElement("tr");
// creating new cells in a row with the data
tableRef.appendChild(row);
}
}
So I'm fetching the reference to my HTML table with var tableRef = document.getElementById('data_table');, in the for-loop, I'm creating rows and appending them to the HTML table with tableRef.appendChild(row);. The problem is that on any sequent $.getJSON call, the table gets further appended. How do I refresh my table on every call, ie. delete data from the previous call, and fill data from a new call?
You can delete the rows after getting the data from the server
$.getJSON("/data/"+data, function(dataState) {
$("#data_table tr").remove();
//...
for(var dataId in dataState) {
var row = document.createElement("tr");
// creating new cells in a row with the data
tableRef.appendChild(row);
}
}
});
Note that it will also remove the headers of the table, if you want to remove the data only and keep the headers, you only remove the rows inside tbody tag i.e $("#data_table tbody tr").remove();
You can use jQuery to delete every children of type tr with $("#data_table tr").remove();.
So you'll have something like this:
var data = $('#data_input').val();
var tableRef = document.getElementById('data_table');
$.getJSON("/data/"+data, function(dataState)
{
// ...
$("#data_table tr").remove();
for(var dataId in dataState)
{
var row = document.createElement("tr");
// creating new cells in a row with the data
tableRef.appendChild(row);
}
}

How to get complete data from (html) bootstrap table when pagination is turned on

I am using bootstrap table in my web page and want to get complete textual data from all table cells, when pagination is on. I have tried the following method and it returns all the data:
var data = $('#' + tableID).bootstrapTable('getData')
Now when i traverse data object to get value for every cell it works fine but, for those cells which have some nested html , for example:
<td class="danger">cell 4</td>
<td>
google
</td>
Now, in this case, i want to get value for second cell as google but it returns me whole html as
google
Any idea, how i can get only textual value.
I can't do any server side operation, I have to achieve this using javascript/jquery. I have also tried using jquery:
function getColData(tableID,colIndex) {
var colArray = $('#' + tableID + ' td:nth-child'+'('+colIndex+')').map(function(){
return $(this).text();
}).get();
return colArray
}
it returns data correctly but only which is visible on active page and i want all the data.
Based on your file on JSFiddle I have modified the JS part as follows, this will get you the text on every td(i.e. text or text content) and not the values of their attributes. Basically this traverses through the DOM searching for tags embedded in ones - except for those on the table header - then obtains the text value.
var table = $('#table'), button = $('#button');
button.click(function() {
var data = [];
table.find('tr:not(:first)').each(function(i, row) {
var cols = [];
$(this).find('td').each(function(i, col) {
cols.push($(this).text());
});
data.push(cols);
});
alert(data);
});
You can see it in action here
UPDATE:
This will get you all data regardless of pagination, also it will strip tags and nested tags.
var table = $('#table'), button = $('#button');
button.click(function() {
var messedData = table.bootstrapTable('getData');
var data = [];
$.each(messedData, function(i, row) {
var rowData = {
'name': row['0'],
'star': row['1'],
'forks': row['2'],
'desc': row['3'],
}
for (prop in rowData) {
var tmp = document.createElement("div");
tmp.innerHTML = rowData[prop];
rowData[prop] = tmp.textContent || tmp.innerText || "";
}
data.push(rowData);
});
console.log(data);
});
You can see it here
Since the actual data is coming in as a string, I don't think bootstrap-table can't differentiate it from the other data. The simple solution I can think of is to use substring() to extract the data from the cells that contain custom html.
http://jsfiddle.net/vwg5Lefz/
The alternative is to go through the generated table <td> and use text() to get the text data from the cells.
http://jsfiddle.net/n0djy60v/

Creating separate arrays from TH data in different tables

I'm having a bit of an issue with some JS/JQuery. I am using some script to create an array from the data within the <TH> tags, then doing some formatting of that data to create new content and styles for a responsive table.
<script>
$( document ).ready(function() {
// Setup an array to collect the data from TH elements
var tableArray = [];
$("table th").each(function(index){
var $this = $(this);
tableArray[index] = $this.text();
});
console.log(tableArray);
alert(tableArray);
// Create class name based on th values and store as variable
var tableString = tableArray.join();
tableString = tableString.replace(/,/g, '_')
tableString = tableString.replace(/ /g, '-')
var tableClass = ".responsive-table."+tableString;
console.log(tableClass);
// Push tableClass variable into the table HTML element
var applyTableClass = tableClass;
applyTableClass = applyTableClass.replace(/\./gi, " ") //converts the style declaration into something i can insert into table tag (minus the dots!)
console.log(applyTableClass);
$( "table" ).addClass( applyTableClass );
// Create a loop which will print out all the necessary css declarations (into a string variable) based on the amount of TH elements
var i = 0;
var styleTag = "";
while (tableArray[i]) {
styleTag += tableClass+" td:nth-of-type("+[i+1]+"):before { content: '"+tableArray[i]+"'; }";
i++;
}
// Push the styleTag variable into the HTML style tag
$('style#jquery-inserted-css').html(styleTag);
// Below is just a test script to check that values are being collected and printed properly (use for testing)
//$('#css_scope').html('<p>'+styleTag+'</p>');
});
</script>
This works great when there is a single table within the page, but not if there is additional tables. The reason is that the loop that creates the array keeps going and does not know to stop and return at the end of one table, then create a new array for the next table. I am imagining that I need to set up a loop that creates the arrays as well.
This is where I am quit stuck with my limited scripting skills. Can anyone please suggest a way to get my code to loop through multiple tables, to create multiple arrays which then create separate style declarations?
You can loop through each table instead of querying all tables at once:
$( document ).ready(function() {
$("table").each(function () {
var tableArray = [];
$(this).find("th").each(function (index) {
var $this = $(this);
tableArray[index] = $this.text();
});
console.log(tableArray);
alert(tableArray);
// Create class name based on th values and store as variable
var tableString = tableArray.join();
tableString = tableString.replace(/,/g, '_')
tableString = tableString.replace(/ /g, '-')
var tableClass = ".responsive-table." + tableString;
console.log(tableClass);
// Push tableClass variable into the table HTML element
var applyTableClass = tableClass;
applyTableClass = applyTableClass.replace(/\./gi, " ") //converts the style declaration into something i can insert into table tag (minus the dots!)
console.log(applyTableClass);
$(this).addClass(applyTableClass);
// Create a loop which will print out all the necessary css declarations (into a string variable) based on the amount of TH elements
var i = 0;
var styleTag = "";
while (tableArray[i]) {
styleTag += tableClass + " td:nth-of-type(" + [i + 1] + "):before { content: '" + tableArray[i] + "'; }";
i++;
}
// Push the styleTag variable into the HTML style tag
$('style#jquery-inserted-css').append(styleTag);
// Below is just a test script to check that values are being collected and printed properly (use for testing)
//$('#css_scope').html('<p>'+styleTag+'</p>');
});
});
Note that I change $("table th") to $(this).find("th"), $("table") to $(this) and $('style#jquery-inserted-css').html(styleTag); to $('style#jquery-inserted-css').append(styleTag);.
Hope this help.

Get selected value from externally created dropdownlist

I'm creating a dynamic menu that fetches dishes from a database and displays them to the user so he can add them to his order. Whenever I retrieve a row from the database I send it to my menuItems class so the columns can be read and the display format is created and inserted into a cell:
foreach (DataRow dr in drc){
//extract the dish data from the row into a cell
TableCell c1 = menuItem.makeItemCell(dr);
//display it
tr.Controls.Add(c1);
table1.Controls.Add(tr);
}
c1 will be a cell that has the dish information along with a quantity dropdownlist and an "add to order" button:
public static TableCell makeItemCell(DataRow dr)
{
TableCell tc = new TableCell();
Image img = new Image();
img.ImageUrl = (string)dr["img"];
tc.Controls.Add(img);
//rest of information adding is omitted for brevity
String myLiteral = "<p>" + "Name: " + (string)dr["NameofDish"] + "</br>";
tc.Controls.Add(new LiteralControl(myLiteral));
//add quantity label and dropdownlist populated with possible quantity values
Label lb = new Label();
lb.Text = "Quantity: ";
DropDownList ddl = new DropDownList();
for (int i = 0; i < 13; i++)
{
String t = i.ToString();
ddl.Items.Add(new ListItem(t, t));
}
//create the add to order button
Button btn = new Button();
btn.Text = "Add to order";
tc.Controls.Add(lb);
tc.Controls.Add(ddl);
tc.Controls.Add(btn);
return tc;
}
My problem is with handling the button click event. All my tries to bind it with an event handler (on the menuItems class or the codebehind itself) have failed. I could only manage to update the postbackURL of the button when it's created in the cell like this
btn.PostBackUrl = "./menu.aspx?dish=" + (string)dr["ID"] + "&quantity=" + ddl.SelectedValue;
But the .selectedvalue value is rendered when the cell is created hence is always 0
My question is this: how can I handle the button click event in a way that I can get hold of the dishID and the selected value.
((((I would prefer an event handling solution rather than querystrings if possible))))
Thank you!
EDIT:
My whole problem is that the cell and its components are created in the external class and sent back to my code. How do I access the dropdownlist variable from my codebehind if I don't have the element id or anything

Categories