Bojangles
Bojangles

Reputation: 101553

.live() and .data()

I'm trying to make a piece of JavaScript that allows me to just add an <input> with a certain class, and it will automatically add placeholder-like behaviour to it. The problem is, I load some inputs in via AJAX. I use the .live() method to get around this, however .data() doesn't want to play.

Here's an example:

jQuery

$(".placeHolder").data("originalValue", $(this).val());

$(".placeHolder").live("focus", function() {
    if($(this).val() == $(this).data("originalValue"))
    {
        $(this).val('');
    }
});
$(".placeHolder").live("blur", function() {
    if(!$(this).val().length)
    {
        $(this).val($(this).data("originalValue"));
    }
});

// Load inputs into an element
$("selector").load("loadInput.php", function(response, status, xhr) {
    $(".placeHolder").data("originalValue", $(this).val());
});

HTML

<input type="text" name="foo" value="Bar" class="placeHolder">

The problem is the fact that the <input>'s original value isn't stored by .data() anywhere - even in the .post() call. There can be more than one .placeHolder on the page.

Am I using .data() incorrectly? If not, what else is going wrong?

Upvotes: 0

Views: 280

Answers (2)

Sean McMillan
Sean McMillan

Reputation: 10093

.live() places an event handler on the document element, which uses event bubbling to catch events, and checks if they come from an appropriate source. .data() attaches data to an existing element. You're using live() because you load your data via AJAX, and it will work regardless of when your <input> elements appear. But data() doesn't work that way.

If you are using a recent enough version of jQuery, you may be able to use HTML5 data- attributes and access them using the data() handler.

Upvotes: 1

Joseph Marikle
Joseph Marikle

Reputation: 78590

@JAAulde has a point...

$(".placeHolder").data("originalValue", $(this).val());

Should be this maybe?

$(".placeHolder").each(function(){
  $(this).data("originalValue", $(this).val());
});

Upvotes: 2

Related Questions