views:

35

answers:

2
+1  Q: 

Strange behaviour

I have the following script which works kind of...

$(document).ready(function(){
    // add or remove from favorites
    $("input:checkbox").change(function() { 
        if($(this).is(":checked")) { 
            $.ajax({
                url: 'favorite.aspx',
                type: 'POST',
                data: { ID:$(this).attr("id"), State:"1" }
            });
        } else {
            $.ajax({
                url: 'favorite.aspx',
                type: 'POST',
                data: { ID:$(this).attr("id"), State:"0" }
            });
        }
    }); 

    // search on keyup
    $(".txtSearchBox").keyup(function() 
    { 
        $.ajax({
            url: 'search.aspx',
            type: 'POST',
            data: { strPhrase:$(".txtHeaderSearch").val() },
            success: function(results) 
            { 
                $("#divSearchResults").empty(); 
                $("#divSearchResults").append(results); 
            }
        });
    });
});

When the page loads for the first time after clearing browser cache, favorites function works fine and so does the search function. However, after loading the page after a page refresh, if I perform a search first, then try to tag a favorite, the favorite will not get inserted into the database, I have to click the reload browser button, then add a favorite.

Why is this happening?

+5  A: 

You need to use live() as you are trying to act on stuff in the dom which you are inserting using ajax.

http://api.jquery.com/live/

DavidYell
Perfect. Thanks!
oshirowanen
A: 

Live is an answer, but I've had problems with change event with live and Internet Explorer, at least with select fields. I've solved the problem by using the livequery plugin.

jQuery delegate should also work if you don't want to install plugins.

MaMa