Removing a row from the table and re indexing the table - javascript

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

Related

Creating a hyperlink within a table cell

I'm attempting to creating a hyperlink within a cell of a table, but currently the hyperlink just displays as text within the table. Looking at the console I can see linkElement is getting created properly as:
text
My JS code
//Creating the table
var table = document.getElementById("myTable");
var row = table.insertRow(0);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
//creating URL elements
linkElement = document.createElement("a");
linkElement.setAttribute("href", url);
var linkText = document.createTextNode(url);
linkElement.append(linkText);
console.log(linkElement)
cell1.innerHTML = linkElement;
cell2.innerHTML = appVersion;
My HTML:
<table id="myTable">
</table>
Use cell1.append(linkElement), cell1.innerHTML is meant to be use when providing the HTML as string not an object.
Figured it out using cell1.innerHTML= ''+linkElement+'';

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

acts_as_votable javascript html table

I'm trying to use the acts_as_votable gem in ruby on rails. However, I get stuck when I need to add the button to the view.
I want to add a voting system to a list of item which are put into an html table as users fill out the form in the web browser.
I can insert a 'like' button in each row for each 'destination' item. However, does this mean I need to write a 'attachLikeHandler' function to deal with what happens when the like button is clicked?
Here is the dashboard.js:
var insertDest = function(dest) {
// Find a <table> element with id="myTable":
var table = document.getElementById("destTable");
// Create an empty <tr> element and add it to the 1st position of the table:
var row = table.insertRow(1);
// Insert new cells (<td> elements) at the 1st and 2nd position of the "new" <tr> element:
var name_cell = row.insertCell(0);
var address_cell = row.insertCell(1);
// var delete_cell = row.insertCell(2);
var like_cell = row.insertCell(2);
like_cell.innerHTML = '<input class="Like" type="button" value="Like" />';
var like_count_cell = row.insertCell(3);
like_count_cell.innerHTML= 0;
// Add some text to the new cells:
name_cell.innerHTML = dest.name;
address_cell.innerHTML = dest.address;
// delete_cell.innerHTML = "<div class='del'>x</div>";
addMarker(dest.address,map);
};
var insertAllDest = function(trip){
var d = trip.destinations;
for (i in d){
insertDest(d[i]);
}
};
However, does this mean I need to write a 'attachLikeHandler' function
to deal with what happens when the like button is clicked?
Yes:
$(".like").on('click', function() {
$.ajax({
method: "PUT",
url: "/photos/" + $(this).attr("id"),
success: function(msg_from_server) {
alert(msg_from_server); //"Thanks for voting!" or "Sorry, you already voted!"
}
});
});
If you have a route declared as resources :photos, then a url like /photos/12 will send a request to photos#update, then inside the update action params[:id] will be 12. Note that you'll need to add the resource id to the html when constructing the html.

Insert HTML table row with JavaScript with different variable names

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.

How to save JavaScript generated content as HTML in the file?

I have a table with 1 row, 11 columns. Now I generated the following JavaScript code to add a new row using a Button.
The issue is, when i refresh the page, the new rows that i added using this javascript, are lost. I want them to be saved permanently in the HTML file. How can this be done?
<script>
function AddNewRow()
{
var table = document.getElementById("table1");
var row = table.insertRow(1);
var cell0 = row.insertCell(0);
var cell1 = row.insertCell(1);
var cell2 = row.insertCell(2);
var cell3 = row.insertCell(3);
var cell4 = row.insertCell(4);
var cell5 = row.insertCell(5);
var cell6 = row.insertCell(6);
var cell7 = row.insertCell(7);
var cell8 = row.insertCell(8);
var cell9 = row.insertCell(9);
var cell10 = row.insertCell(10);
</script>
The HTML file remains on a server inaccessible to the client, but it would be perfectly possible for the browser to save the added information - either in HTML form, or as a more storage-focused format like XML/JSON. It would then need to be loaded back into Javascript and re-added to the page each time your page starts up.
Read up on the localStorage documentation at Mozilla - they could give you a general idea of storing/loading. With the innerHTML readable/writable property, hopefully you have an idea of how you could accomplish this.
https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Storage#localStorage

Categories