views:

19

answers:

1

Hi!

I have a jQuery application, a shopping cart, that posts back info to the server, if the text inputfield is changed. This is done in an Ajax request. Now, if the Ajaxrequest is a success, I want to reload the shoppingcart asynchronously. The code is as follows:

$(document).ready(function() {

    var jInput = $(":input");
    jInput.change(function() {
        var vareAntal = $(this).val();
        var vareID = $(this).siblings("input#vareID").val();
        $.ajax({
            type: 'POST',
            url: 'checkout.aspx',
            data: { 'ID': vareID, 'Antal': vareAntal },
            success: function() {
                $("#newbasket").load(location.href + " #newbasket>*", "");
            }
        });
    });
});

This works, but only once! If I change the text inputfield, after the page is loaded for the first time, the div with the ID of newbasket reloads asynchronously. But if I try to change it again, nothing happens.

I've tried to do some debugging with Firebug, and the first time I change the text inputfield, it fires a POST-event, and afterwards a GET-event, when the POST-event is succesful. But after that, nothing happens when I change the text inputfield again.

So, how do I achieve triggering the .load() method after each text input change?

I've also tried experimenting with the .ajaxComplete() function, but that, of course, resulted in an infinite loop, since the .load() is an ajax-object.

+1  A: 

Instead of .change(func), use .live('change', func) here, like this:

jInput.live('change', function() {

This will make the selector work on any new inputs added as well. When you're replacing the elements like you are currently, their event handlers are lost (or rather, not re-created, because you have new elements). .live() is just for this purpose, it listens for events from old and new elements, regardless of when they were added.

Nick Craver
Thanks, this works like a charm!
Mads U.O.