UXerUIer
UXerUIer

Reputation: 2338

The relation between .load and .ready

I'm loading a part of a page into another page using the .load function in jQuery

$("#loadingDockShotPg").load("include/shot_comments.php?id="+get['id']);

In my file that's being loaded into the div with the id "loadingDockShotPg" there are elements in there in which I would like to be effected by my jQuery commands.

The HTML that's being placed into another page using .load

 <textarea id='newNoteTextarea' class='width100 hidden' placement='Write a comment...'></textarea>

The jQuery that's placed in the parent file that the HTML above is being placed in

    $(document).ready(function(){
        $("input[placement], textarea[placement]").each(function(){
        var orAttr = $(this).attr("placement");

        $(this).val(orAttr);

        $(this).focus(function(){
            if($(this).val() == orAttr)
            {
                $(this).val("");
            }
        });
        $(this).blur(function(){
            if($(this).val() == "")
            {
                $(this).val(orAttr);
            }
        });
        });
    });

The problem is that my textarea isn't being affected by the jQuery that's supposed to put the placement attribute in the textarea's value. What do I have to do in order to have this work?

Upvotes: 0

Views: 60

Answers (2)

Marwelln
Marwelln

Reputation: 29433

Your .load() is a "live function". You are adding content to the DOM after it has been loaded. Your .each() function have already been executed before your content is added with the .load(). To fix this you can run your .each() function when .load() is complete as a callback.

This is how I should have done it:

$(function(){
    var inputElements = $("input[placement], textarea[placement]");

    function setInputValue() {
        var self = $(this),
            orAttr = self.attr("placement");

        self
            .val(orAttr)
            .focus(function(){
                if(self.val() == orAttr)
                {
                self.val("");
                }
            })
            .blur(function(){
                if(self.val() == "")
                {
                self.val(orAttr);
                }
            });
    }

    inputElements.each(setInputValue);

    $("#loadingDockShotPg").load("include/shot_comments.php?id="+get['id'], function(){
        inputElements = $("input[placement], textarea[placement]");
        inputElements.each(setInputValue);
    });
});

Upvotes: 1

Mike Sav
Mike Sav

Reputation: 15321

You may want to look at using .live(), (which is technically depreciated) or .on() to attach/bind to events on selected elements when using .load()

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

http://api.jquery.com/on/

Upvotes: 1

Related Questions