mfalcon
mfalcon

Reputation: 880

.click() event executed only the first time

I have the next script, "/cashflow/arrow/" calls a django view that gets the data and works with it. Then it returns the data that is loaded in the html.

The script works fine in the first click, but when I want to click a link again, nothing happens.

<script>
$(document).ready(function(){   
    var prev_months = {{ prev_months }}
    var next_months = {{ meses_desp }}  

    function arrow(meses_ant, next_months) {
        $.get("/cashflow/arrow/", { prev_months: prev_months,   next_months: next_months},
          function(data){
            $("#cash_grid").html(data);      
         });
    }

    $("#dates_up").click( function() {
        if (prev_months > 0) {
            prev_months = prev_months - 1;
        }
        next_months = next_months + 1;
        arrow(prev_months, next_months);
    });
    $("#dates_down").click( function() {
        prev_months = prev_months + 1;
        if (next_months > 0) {
            next_months = next_months - 1;
        }
        arrow(prev_months, next_months);
    });

})

Upvotes: 1

Views: 2415

Answers (2)

pedrorezende
pedrorezende

Reputation: 288

Try to use .live("click", function() {...}); instead the click event. Eg:

$("#dates_up").live("click", function()...
$("#dates_down").live("click", function()...

You can read more about it here

Upvotes: 2

Steve Jalim
Steve Jalim

Reputation: 12195

By any chance, does the HTML you're returning contain a new version of the elements with the ids #dates_up and #dates_down? That is to ask: do they live inside #cash_grid?

If so, then the click events you bound in document.ready are lost when the HTML is updated, so you'll have to rebind those click events.

The easiest way to do this is to put your click() binding code in a separate function, call it in document.ready() to set up the binds and then also call it in the AJAX get() callback to set new binds on the new elements that have been returned

Upvotes: 1

Related Questions