views:

52

answers:

3

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);
    });

})

A: 

I'm not sure, but shouldn't function arrow be outside the scope of $(document).ready ? I'm guessing execution is getting to this step (last line of either onclick), failing, and then won't get called again.

Rudu
+1  A: 

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

stevejalim
Or, indeed, you could use live() as pedro says
stevejalim
Thanks Steve!, your solution also worked fine.
mfalcon
+1  A: 

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

pedrorezende
Thanks Pedro!, It worked!
mfalcon