Javascript Onclick with Table Rows
javascriptTo add an onclick event to table rows in JavaScript, you can use the addEventListener method to attach an event listener to each row in the table. Here’s an example:
<table id="myTable">
<thead>
<tr>
<th>Name</th>
<th>Email</th>
<th>Phone</th>
</tr>
</thead>
<tbody>
<tr>
<td>John Smith</td>
<td>[email protected]</td>
<td>555-1234</td>
</tr>
<tr>
<td>Jane Doe</td>
<td>[email protected]</td>
<td>555-5678</td>
</tr>
</tbody>
</table>
<script>
var table = document.getElementById('myTable');
var rows = table.getElementsByTagName('tr');
for (var i = 0; i < rows.length; i++) {
rows[i].addEventListener('click', function() {
// Do something when a row is clicked
console.log('Row clicked: ' + this.cells[0].textContent);
});
}
</script>
In this example, we first get a reference to the table using getElementById. We then get all the rows in the table using getElementsByTagName(‘tr’). We iterate through each row using a for loop and attach an onclick event listener to each row using addEventListener.
When a row is clicked, the event listener function is called and the this keyword refers to the clicked row. In this example, we simply log the text content of the first cell in the row to the console.
You can modify the event listener function to perform any action you want when a row is clicked, such as highlighting the row or displaying additional information.
Other Article on Tag javascript
- - Adding and removing content in jQuery
- - Are JavaScript strings immutable? Do I need a "string builder" in JavaScript?
- - Can I change the Dojo namespace to something other than dojo
- - Can I prevent user pasting Javascript into Design Mode IFrame
- - dynamically create html element in javascript
- - Find XY of an HTML element with JavaScript
- - How can I upload files asynchronously with jQuery
- - How can you display Typing Speed using Javascript or the jQuery library
- - How do you capture mouse events in firefox
- - How to auto-size an iFrame