Forum Moderators: open
I have a script that creates a menu of image buttons dynamically.
function addRow() {
var myBody = document.getElementById('displayButton')
.getElementsByTagName('tbody')[0];
var row = myBody.appendChild( document.createElement('tr'));
for (var i=0, cell; i < arguments.length; i++) {
cell = document.createElement("td");
row.appendChild(cell);
cell.appendChild(document.createTextNode( arguments[i]) );
cell.onclick = cell_click;
}
}
function cell_click() {
var i = this.cellIndex;
document.picture.src = display[i];
document.getElementById("imgName")
.getElementsByTagName('td')[0].nodeValue = myPic_name[i];
document.getElementById("imgDescript")
.getElementsByTagName('td')[0].nodeValue = myPic_descript[i];
}
This code works great thanks to forums like these. But because I am new to JavaScript, I like to start new threads, whenever I have new issues, so that other new guys can have a reference for specific actions.
This script creates the image list depending on how many arguments are passed.
onclick = addRow(pic1, pic2, pic3)
would render something allong the lines of this
pic1 pic2 pic3
problem is when onclick = addRow(pic1, pic2, pic3) is clicked again it just adds on to the table. It looks like
pic1 pic2 pic3
pic1 pic2 pic3
Instead, I want it to delete the first nodes rendered then rewrite them over. So, it will still look like
pic1 pic2 pic3
This is what I have so far:
function addRow() {
var myBody = document.getElementById('displayButton')
.getElementsByTagName('tbody')[0];
//the following can be emmited until the next '//'.
if (myBody.length) {
var allCells = myBody.item(myBody.length - myBody.length);
docbody = document.getElementsByTagName("body").item(0);
removed = docBody.removeChild(allCells);
var row = myBody.appendChild( document.createElement('tr'));
for (var i=0, cell; i < arguments.length; i++) {
cell = document.createElement("td");
row.appendChild(cell);
cell.appendChild(document.createTextNode( arguments[i]) );
cell.onclick = cell_click;
}
}
else {
//
var row = myBody.appendChild( document.createElement('tr'));
for (var i=0, cell; i < arguments.length; i++) {
cell = document.createElement("td");
row.appendChild(cell);
cell.appendChild(document.createTextNode( arguments[i]) );
cell.onclick = cell_click;
//the following can be emmited until the next '//'.
}
//
}
}
function addRow()
{
var myBody, row, cell, i;
myBody = document.getElementById('displayButton')
.getElementsByTagName('tbody')[0];// Remove row[0], if present
if( row = myBody.getElementsByTagName('tr')[0] )
myBody.removeChild(row);
// Carry on as before
row = myBody.appendChild( document.createElement('tr'));for (i=0; i < arguments.length; i++) {
cell = row.appendChild(document.createElement("td"));
cell.appendChild(document.createTextNode( arguments[i]) );
cell.onclick = cell_click;
}
}