ASM wrote:
Daz a écrit :
Hello everyone. I am sure the answer to my question is simple, but I
can't seem to dynamically add an onClick event to my script.
I have a table which is generated dynamically, I am just struggling
getting an onClick event to show in the HTML source.
Any help would be appreciated. Here is a block of my current code which
doesn't work.
var tr1 = document.createElement('tr');
tr1.style.backgroundColor = "blue";
var td1 = document.createElement('td');
var titleSpan = document.createElement('span');
titleSpan.style.color = "white";
titleSpan.style.fontWeight = "bold";
titleSpan.onClick = function() {this.toggle(); };
titleSpan.innerHTML = menuTitle;
td1.appendChild(titleSpan);
tr1.appendChild(td1);
tbody.appendChild(tr1);
use tbody instead of table
.
Thanks ASM. my table variable is actually a reference to tbody. You're
right, though. I should have named it tbody and not table.
I still can't get it to work. For some reason, the toggle function is
not working at all. I have tried adding the function to the onClick
event directly, and it still doesn't work... I don't even get an
error/warning in my JavaScript Console...
I know it's something I am doing wrong, I just can't figure out what.
Here is my code. It looks messy because I am trying to figure out how
things work...
//********** CODE START **********
var table = document.getElementById('ctg_table');
var tableWidth = 80;
function initPage()
{
table.parentNode.style.width = tableWidth + "%";
displayInputDialog();
var row1 = new menuItem("test");
}
function displayInputDialog()
{
var tr = document.createElement('tr');
tr.setAttribute("id", "rInputDialog");
tr.style.height = "20%";
var td = document.createElement('td');
textarea = document.createElement('textarea');
textarea.setAttribute("name", "inputDialog");
textarea.setAttribute("id", "inputDialog");
textarea.style.width = "100%";
textarea.style.height = "100%";
textarea.style.borderStyle = "ridge";
table.appendChild(tr);
tr.appendChild(td);
td.appendChild(textarea);
}
function menuItem (menuTitle)
{
var tr1 = document.createElement('tr');
tr1.style.backgroundColor = "blue";
var td1 = document.createElement('td');
var b = document.createElement('b');
var titleSpan = document.createElement('span');
titleSpan.style.color = "white";
table.appendChild(tr1);
tr1.appendChild(td1);
td1.appendChild(b);
b.appendChild(titleSpan);
titleSpan.innerHTML = menuTitle;
var tr2 = document.createElement('tr');
var td2 = document.createElement('td');
table.appendChild(tr2);
tr2.appendChild(td2);
tr2.style.borderStyle = 'ridge';
tr2.style.borderColor = "green";
td2.innerHTML = 'blah';
titleSpan.onClick = function()
{
var textarea = document.getElementById('inputDialog');
textarea.value = "blah"
}
}
initPage();
//************ CODE END ************
Many thanks for your input.
If you can offer any more constructive criticism, it would be received
gracefully as I would rather do this right, than go about it the wrong
way.
Daz.