jQuery

jQuery Table Row Click Examples

While working with web pages & data, there might have been times when you need to show data with the help of tables and at some point or the other, you might have felt the need to attach functionality to table, especially table row. One such event, for example, would be the table row click event. In this article, I am going to share a very simple way to check/find out/ determine if a table row was clicked using jQuery. Read on to find out more.

Examples to Check if Table Row was clicked using jQuery

Let’s discuss this situation with an example. Let’s assume that we have a table with couple of rows & couple of columns. Now we would like to alert a custom message when a table row was clicked. It could be the first row the second, the last or any other row in the middle. We want to attach a check so that regardless of the row that was clicked, we need to see an alert that shows a custom message. In real time, you might want to replace the alert message with a custom action. So for the sake of simplicity, let’s see how we can check if a table row was clicked using jQuery.

Example: Full source code to check if table row was clicked using jQuery

<html>
<head>
<title>Example to Check if Table Row was clicked using jQuery</title>
<script type="text/javascript" src="js/jquery_1.7.1_min.js"></script>
</head>

<body>

<table width="100%" border="0" cellspacing="0" cellpadding="0">
<tr bgcolor="#CCCCCC">
<td>asd</td>
<td>aa</td>
</tr>
<tr bgcolor="#FFCC66">
<td>cc</td>
<td>asd</td>
</tr>
</table>
<script type="text/javascript" language="javascript" >

$(document).ready(function(){

$('tr').click(function() {

alert('Row was clicked');

});

});
</script>
</body>
</html>

Simply run the above code & click on any row. You will see the alert message “Row was clicked”. If you would like to determine if a cell was clicked, rather than a row, then simply replace the above code with the following code:

$('td').click(function() {

alert('Cell was clicked');

});

When you run the modified code above, you will see the alert “Cell was clicked”. There may not seem to be much difference in terms of functionality for now, as we are dealing with a very basic example. The limit to the scope of enhancement to this example is only your imagination.

I hope that helped you understand how we can determine if table row was clicked by using click event on a table row, using jQuery. If you would like to perform more operations, such as get row number & column numbers of a table, get row index & column index, then I have already written a separate article that you might want to read. Check out this article: jQuery Get Row Number & Column Number examples

Your Turn!

Do you know of any other ways to determine / check if table row /cell was clicked using jQuery? Feel free to suggest by commenting below.

Share your thoughts, comment below now!

*

*