I have an HTML table created with dynamic data and cannot predict the number of rows in it. What I want to do is to get the value of a cell when a row is clicked. I know to use td onclick but I do not know how to access the cell value in the Javascript function.
The value of the cell is actually the index of a record and it is hidden in the table. After the record key is located I can retrieve the whole record from db.
How to get the cell value if I do not know the row index and column index of the table that I clicked?
This is my solution
You can use:
With passing this you can access the DOM object via your function parameters.
Don't use in-line JavaScript, separate your behaviour from your data and it gets much easier to handle. I'd suggest the following:
JS Fiddle proof-of-concept.
A revised approach, in response to the comment (below):
This revision binds a (single) named function as the
click
event-handler of the multiple<td>
elements, and avoids the unnecessary overhead of creating multiple anonymous functions within a loop (which is poor practice due to repetition and the impact on performance, due to memory usage):JS Fiddle proof-of-concept.
References:
Array.prototype.forEach()
.document.getElementById()
.document.getElementsByTagName()
.document.querySelectorAll()
.EventTarget.addEventListener()
.Function.prototype.call()
.I gave the table an id so I could find it. On onload (when the page is loaded by the browser), I set onclick event handlers to all rows of the table. Those handlers alert the content of the first cell.
.......................
I wrote the HTML table in JSP. Course is is a type. For example Course cs, cs= object of type Course which had 2 attributes: id, title. courses is an ArrayList of Course objects.
The HTML table displays all the courses titles in each cell. So the table has 1 column only: Course1 Course2 Course3 ...... Taking aside:
This means that after user selects a table cell, for example "Course2", the title of the course- "Course2" will travel to the page where the URL is directing the user:
http://localhost:8080/Mydata/ComplexSearch/FoundS.jsp
. "Course2" will arrive in FoundS.jsp page. The identifier of "Course2" is courseId. To declare the variable courseId, in which CourseX will be kept, you put a "?" after the URL and next to it the identifier. It works.