I have a page that allows users to edit their data (On the database). I have a JavaScript that inserts rows. Those rows contain textboxes whose values are stored in different variables. So, i need a way to insert a table row that has the same structure, but different variable names.
In order to insert/edit data at the same time, i need different values on different fields. (The insertion/editing is made on the edited.php page)
JavaScript:
<script type="text/javascript">
function addRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var colCount = table.rows[0].cells.length;
for(var i=0; i<colCount; i++) {
var newcell = row.insertCell(i);
newcell.innerHTML = table.rows[1].cells[i].innerHTML;
//alert(newcell.childNodes);
switch(newcell.childNodes[0].type) {
case "text":
newcell.childNodes[0].value = "";
break;
case "checkbox":
newcell.childNodes[0].checked = false;
break;
case "select-one":
newcell.childNodes[0].selectedIndex = 0;
break;
}
}
}
</script>
This Script inserts a table row on my html table. That insertion is made by copying the first table row. I need a NEW row with NEW variables.
Is there anyway to define the row that is inserted?
You can use the javascript createElement function, here is a little example that should get you on your way:
function addNewRow(tableID) {
var table = document.getElementById(tableID);
var row = document.createElement('tr');
var data = document.createElement('td');
var tbx = document.createElement('input');
tbx.setAttribute('type', 'text');
data.appendChild(tbx);
row.appendChild(data);
table.appendChild(row);
}
it should be fairly self-explanatory, create an element, set its attributes, and add children elements to it, in your case: textbox, checkbox etc.
If you need to have dynamic ids and/or values, add a counter variable and increment as you go along and/or add parameters like
function addNewRow(tableID, input1, input2, input3){}
You can assign the name to each row you create dynamically like this:
var row_counter=0 // have a global counter
var row = table.insertRow(rowCount);
row.setAttribute("id", "row"+row_counter);
//NOW INCREMENT THE COUNTER BASED ON YOUR LOOP
You can work out the loop in a way you want.
Related
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;
}
});
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);
}
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);
}
}
I need your assistant in getting the total number of rows for each printed table in my html to be shown at the top of it.
I am having multiple tables in the html which their id is unique "detailsTable". Each table has different number of rows. I search for a script to print the total number of rows and I found the below script:
function count()
{
var rows = document.getElementById("detailsTable").getElementsByTagName("tr").length;
alert(rows);
}
and in the body tag, I placed:
<body onload="count()">
When I ran the page, it shows an alert for the first table which it has 22 records and the script ignores the below tables.
So, can you please help me to modify the above code and to display the alert for the other tables.
The id should be unique for every html element.
You can use class instead, and then:
function count()
{
var tables = document.getElementsByClassName("detailsTable");
var rows;
for (var i = 0; i < tables.length; i++) {
rows = tables[i].rows.length;
alert(rows);
}
}
If you want to count table rows with id = "detailsTable"
var rowCount = $('#detailsTable tr').length;
If you want to find it for every table, it would look something like:
$('.details').each(function(index) {
var rowCount = this.rows.length;
})
I'm trying to create a button to put in the each row of a table to remove that row
the table row it self will be created by javascript on the runtime
function createrow(){
document.getElementById('totaltd').innerHTML = total;
var table = document.getElementById('baskettbl');
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var cell2 = row.insertCell(0);
cell2.innerHTML='deleterow';
var cell2 = row.insertCell(1);
cell2.innerHTML='price';
var cell3 = row.insertCell(2);
cell3.innerHTML='name';
}
here is my removing row function
function removerow(i){
var table = document.getElementById('baskettbl');
table.deleteRow(i);
}
my problem is when i remove a row if that row is in the middle of my table it will mess up the indexing cuz i define removerow argument when i creat each row
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var cell2 = row.insertCell(0);
cell2.innerHTML='<a href="" onclick="removerow('+rowCount+'); return false; />
like if i have 5 rows and and i remove row[3] i will end up with 4 rows but my last row button is still going to pass 5 to the removerow function and of course there is no row[5]
so i thought i should re index all of the rows by simply
function removerow(i){
var table = document.getElementById('baskettbl');
table.deleteRow(i);
}
var rowCount = table.rows.length;
for(i=0 , i<= rowCount ; i++){
var cell = 'cell'+i;
cell.innerHTML='<a href="" onclick="removerow('+0+'); return false; />
}
but i need to set the td id in the numeric whey so i can change their innerhtml like this
so here is my questions :
1.how can i set the attribute like id to the created td so i can get their values later? here is how i create them
var cell2 = row.insertCell(0);
2.i findout about rowIndex property which apparently returns the row index
function removerow(x)
{
alert("Row index is: " + x.rowIndex);
}
so that is going to make my job easy and i don't need to recreate all the indexes but how can i pass the clicked row 'this' to the the function ? here is how i pass the index
var cell2 = row.insertCell(0);
cell2.innerHTML='<a href="" onclick="removerow('+rowCount+'); />
and also i use dreamweaver cs5 and it doesn't seems to recognize rowIndex
Then get the index dynamically and don't set it when you create it:
function createrow(){
document.getElementById('totaltd').innerHTML = total;
var table = document.getElementById('baskettbl'),
rowCount = table.rows.length,
row = table.insertRow(rowCount),
cell = row.insertCell(0),
a = document.createElement('a');
a.href = '#';
a.innerHTML = 'deleterow';
a.onclick = function() {
// `this` refers to the `a` element.
removerow(this.parentNode.parentNode.rowIndex);
return false;
};
cell.appendChild(a);
cell = row.insertCell(1);
cell.innerHTML='price';
cell = row.insertCell(2);
cell.innerHTML='name';
// still needed for IE memory leak? Don't know...
table = row = cell = a = null;
};
Setting the click event handler via JavaScript is more readable anyway (well, you could also just use this.parentNode.... in the HTML string).
The code above should do what you want (if you have questions about it, just comment). Nevertheless I wanted to answer your questions:
how can i set the attribute like id to the created td so i can get their values later?
An important thing to know is that there is a difference between HTML attributes and DOM properties. These answers describe it quite well, although it is originally about jQuery (but that does not matter).
Anyway, you already know how to set the innerHTML and you can do so similar for id:
cell.id = "something";
Have a look at the DOM element reference.
but how can i pass the clicked row 'this' to the the function
I more or less showed this in the code above. Inside the event handler, this refers to the element you bound the event to. We know that it is an a element which is a child of a td element, which itself is a child of a tr element. So to get the corresponding row, we can access this.parentNode.parentNode.
For further information regarding JavaScript, have a look at the javascript tag information page. There you will find a lot of useful links to introductions about various JavaScript related topics.
Especially have a look at the articles about event handling at quirksmode.org.
Try this I hope this helps you.
function createrow(){
document.getElementById('totaltd').innerHTML = total;
var table = document.getElementById('baskettbl');
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
row.id = "row_"+rowCount;
var cell2 = row.insertCell(0);
cell2.innerHTML='deleterow';
var cell2 = row.insertCell(1);
cell2.innerHTML='price';
var cell3 = row.insertCell(2);
cell3.innerHTML='name';
}
function removerow(i){
var table = document.getElementById('baskettbl');
table.removeChild(document.getElementById("row_"+i));
}