jhamm
jhamm

Reputation: 25062

Ajax call happening 2 times in a row?

I have a rails application that I am working on that exhibiting behavior I cant understand. I have an html file:

<h1>Hello World</h1>
  <table>
    <tr>
        <td>Hello</td>
    </tr>
    <tr>
        <td>Hello</td>
    </tr>
    <tr>
        <td>Hello</td>
    </tr>
    <tr>
        <td>Hello</td>
    </tr>
</table>

I then have a javascript(jquery really) file that I hit when someone clicks on a row in the table.

$(document).ready(function(){
  $("tr", "table").click(function(){
    console.log("TEST");
  });
});

Everytime I click on a row in the table, the function is called 2 times. I get 'TEST' in the console twice. I am new to jquery and rails, so I know that I am missing something simple. Someone please show me what I am doing wrong.

Upvotes: 0

Views: 162

Answers (3)

Scott Selby
Scott Selby

Reputation: 9580

THe click is being fired for the table click and the tr click try this

$(document).ready(function(){
  $("tr").click(function(){
    console.log("TEST");
  });
});

you don't need a click event on table , unless you want to be able to click in the table- but not in a row , that doesn't sound right

Upvotes: 0

Robyflc
Robyflc

Reputation: 1209

As the guys stated, it's happening because each tr is inside a table so it's a correct behavior. If you wanna avoid it, I believe that preventing the event propagtion would work:

$(document).ready(function(){
  $("tr", "table").click(function(e){
    e.stopPropagation();
    console.log("TEST");
  });
});

Upvotes: 2

Jason
Jason

Reputation: 2364

It's counting the click for both the "tr" and the "table"

Try

$(document).ready(function(){
  $("tr").click(function(){
    console.log("TEST");
  });
});

Upvotes: 2

Related Questions