Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Click event on table row - only trigger if nothing else is 'clicked'

Tags:

jquery

onclick

I'm having some issues with some jQuery code, and I'm hoping and thinking that the solution is relatively simple.

Say I have a table like:

<table>
   <tr>
     <td><input type="checkbox" name="hai" value="der" /></td>
     <td><a href="mypage.php">My link</a></td>
     <td>Some data</td>
     <td>Some more data</td>
   </tr>
   ...
</table>

Now through JavaScript I do the following in jQuery(document).ready();

jQuery("table tr").click(function(){
   var row = jQuery(this);
   var hasClass = row.hasClass("highlight");
   jQuery("table tr").removeClass("highlight");
   if(!hasClass){
     row.addClass("highlight");
   }
});

All of this is pretty simple stuff - I want to be able to click a row and have it being highlighted and only one row can be highlighted at a time (obviously in my actual code I do more than that) - now here's my problem:

When a user clicks the anchor tag, or the checkboxes, this triggers the row click event as well and I cannot work out how to filter that out? I know I need to include the event in my click handler, but how to check for this in a such way that it works in as many browsers as possible?

like image 610
kastermester Avatar asked May 18 '09 11:05

kastermester


People also ask

How do I trigger a click event without clicking?

If you want to trigger click event without clicking a button manually, then you should use the click() method in Javascript. Example : click button on page load dynamically. For that we will create a button with an id my-btn . So that, we can select the button using the getElementById() method.

How do you trigger an event on click?

The HTMLElement. click() method simulates a mouse click on an element. When click() is used with supported elements (such as an <input> ), it fires the element's click event. This event then bubbles up to elements higher in the document tree (or event chain) and fires their click events.

How do you make a row clickable react in a table?

We can make a single cell clickable in row by applying an onClick event on the data of that cell and make it an anonymous function for passing cell value.


2 Answers

Try adding handlers to the other elements that respond to click events and stop the event from bubbling up. This would be in addition to what you already have.

jQuery('table input, table a').click( function(e) {
    e.stopPropagation();
    return true;
}):
like image 79
tvanfosson Avatar answered Oct 11 '22 15:10

tvanfosson


$("table tr").click(function(event){
   if (event.currentTarget.tagName != "TR") { return; }

   $(this).closest("table").find("tr.highlight").removeClass("highlight");
   $(this).addClass("highlight");
});
like image 31
Chad Grant Avatar answered Oct 11 '22 14:10

Chad Grant