Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
55
rated 0 times [  58] [ 3]  / answers: 1 / hits: 39147  / 12 Years ago, thu, july 5, 2012, 12:00:00

I'm trying to convert a table I've written in HTML into Javascript because I want the table to be dynamically generated (# of rows). The main issue I'm having is that the individual cells in the table are clickable and open up another html page. Unfortunately, the html onclick parameter doesn't work with document.write statements Here is an examples of a table cell in HTML:



<td id=r1c1 align=center onclick=getTicket(1,'plan',1);><script language=JavaScript>document.write(getDate(1,plan, r1c1)); </script></td>


The functions in this line are predefined and work so I'm not going to post those, but the idea is that the function getTicket(..) is suppose to open up another html page.



My issues is how to get the onclick to work in JavaScript. I can create the cells in Javascript using document.write commands but don't really know how to make those cells clickable to run the function getTicket(..).


More From » html

 Answers
43

Your style of Javascript programming is ancient, to say the least. document.write is a function developed mainly when there were almost no common methods to generate dynamic content.



So, you should generate your elements dynamically with methods like document.createElement, append your content there, then attach the elements to the DOM with modern methods like appendChild.



Then, you can attach event listeners using something more modern than the traditional way like onclick, like addEventListener. Here's a snippet:



var td = document.createElement(td);
td.innerHTML = getDate(1, plan, r1c1);
td.addEventListener(click, function() {
getTicket(1, 'plan', 1);
});
row.appendChild(td);


I supposed that row is the row of the table that you're generating.



Unfortunately, IE<9 uses a different method called attachEvent, so it'd become:



td.attachEvent(onclick, function() { ...

[#84441] Wednesday, July 4, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jaleelh

Total Points: 661
Total Questions: 125
Total Answers: 103

Location: Sweden
Member since Mon, May 8, 2023
1 Year ago
;