Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery function gets called twice for each click

Tags:

jquery

Setup:

I have written a jQuery function to update table cells of table_2, when a row in table_1 is clicked. Here is what I have written:

    <script type="text/javascript">
        $("tr").live('click',function() {
            var host = $(this);
            alert('A row in table 1 is clicked!');

            var count = host.find("td").eq(2).text();
            $("#myTable_2 tr:eq(0) td:eq(1)").text(count);
            $("#myTable_2 tr:eq(1) td:eq(1)").text(5);
        });
    </script>

The Problem:

When I step-through this function using FireBug, I can see the cell data in myTable_2 is being changed. BUT, for every click, the function is executed twice. I can see the alert box appearing twice for each click.

Can somebody tell me why does this happen? And how to avoid this?

like image 322
Bhushan Avatar asked May 06 '12 19:05

Bhushan


1 Answers

just simply avoid the propagation of the click

$("tr").live('click',function() {

        ...

        $( event.toElement ).one('click', function(e){ e.stopImmediatePropagation(); } );
    });
like image 149
Paulo Almeida Avatar answered Nov 15 '22 18:11

Paulo Almeida