Search code examples
jqueryfindlive

live find in jQuery


I use the find method in jQuery to find a specific box on the page.

I have other buttons that create new boxes without page-refresh. These new boxes are then NOT found with find, which is a problem.

I use:

$("fieldset#"+new_item_id).find("div.images").append(img);

but am thinking of how to implement the live method also. Or should I use on or other? This live updating stuff is tough.


Solution

  • You would have to call a function on each event to achieve this.

    function addImg( new_item_id, img ){
        $("fieldset#"+new_item_id).find("div.images").append(img);
    }
    

    For those elements already present you'd have to call this on page load. For each added element you call it again. So you'd end up with something like:

    $(function(){
        $("fieldset[id]").each(function(){
            var img = //how ever you find this image...
            addImg($(this).attr('id'),img);
        });
    
        $('button').click(function(){
            //some ajax call
            $.ajax(
                // what ever options you have for url, data etc etc.
                success: function(response){ // assuming response is just the markup
                    var $el = $(response);
                    $('#content').append($el); // how ever you add this content - its probably NOT #content but you'll know that...
                    var img = //how ever you find this image...
                    addImg( $el.attr('id'), img );
                }
            );
        });
    });
    
    function addImg( new_item_id, img ){
        $("#"+new_item_id).find("div.images").append(img);
    }
    

    EDIT - rather than hav the function find the element just pass it in...

    $(function(){
        $("fieldset[id]").each(function(){
            var img = //how ever you find this image...
            addImg($(this),img);
        });
    
        $('button').click(function(){
            //some ajax call
            $.ajax(
                // what ever options you have for url, data etc etc.
                success: function(response){ // assuming response is just the markup
                    var $el = $(response);
                    $('#content').append($el); // how ever you add this content - its probably NOT #content but you'll know that...
                    var img = //how ever you find this image...
                    addImg( $el, img );
                }
            );
        });
    });
    
    function addImg( $newEle, img ){
        $newEle.find("div.images").append(img);
    }