Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery click handler not working in a table [duplicate]

I am using a Jquery plugin called Jquery Content Panel Switcher. It does exactly what the title says, it switches out divs with ease. The html for the page is:

<!--The switcher buttons, basic anchor tags, with the switcher class -->
<a id="content1" class="switcher">One</a>
<a id="content2" class="switcher">Two</a>

<!-- The panel you wish to use to display the content -->
<div id="switcher-panel"></div>

<!-- The actual content you want to switch in and out of the panel, this is hidden -->
<div id="content1-content" class="switcher-content show"></div>
<div id="content2-content" class="switcher-content show"></div>

In each of my content panels I have a form. In each form there is a table:

<table class="table table-hover" data-controller="rank">
  <thead>
    <tr>
      <th colspan="4" align="left"><h2>Rank 1</h2></th>
    </tr>
    <tr>
      <th>Number</th>
      <th>Requirements</th>
    </tr>
  </thead>
  <tbody>
    <tr data-name="one_li">
      <td>1</td>
      <td>Info</td>
    </tr>
    <tr data-name="two_li">
      <td>2</td>
      <td>More Info</td>
      </td>
    </tr>
  </tbody>
</table>

I am trying to fire off an action if a row gets clicked. Here is the javascript I am using:

$(document).ready(function(){
  $('#switcher-panel form table tbody tr').click(function(){
     console.log("Clicked");
   });
});

When I use the Jquery selector of $('#switcher-panel form table tbody tr') in my Chrome console, it finds the table and everything looks fine. When I put it in my javascript file, nothing happens. Some direction would be great. Thanks for the help.

like image 341
jhamm Avatar asked Nov 22 '12 14:11

jhamm


2 Answers

This will work:

$('#switcher-panel').on('click', 'table tr', function() {
    console.log("Clicked", this);
});

Example

This adds a listener to the #switcher-panel that listens for click events on it's children, if the clicked child falls under the 'table tr' selector.

Check out this artice for more info about event delegation. (Ctrl+f for Event delegation)

like image 71
Cerbrus Avatar answered Nov 19 '22 20:11

Cerbrus


If the content of the panel is dynamically appended you would need to delegate the click event to a static parent element. Try this:

$('#switcher-panel').on('click', 'form table tbody tr', function(){
    console.log("Clicked");
});

My guess would be you could shorten the child selector to table tr as well.

like image 3
Rory McCrossan Avatar answered Nov 19 '22 19:11

Rory McCrossan