curly_brackets
curly_brackets

Reputation: 5598

Get `this` from outside a function

How, or is it even possible, to get the this value from a function? I've made this snippet which saves defaultValue on the function, but I would like to read this from outside the function, directly on the dom element. Is that possible??

I've made this, in jQuery:

$("input").val(function() {
    var $label = $("label[for='" + $(this).attr("id") + "']");
    this.defaultValue = $label.text();
    $label.hide()
    return this.defaultValue
}).click(function() {
    if ($(this).val() == this.defaultValue) {
        $(this).val("");
    }
}).bind("blur", function() {
    if ($(this).val() == "") {
        $(this).val(this.defaultValue);
    }
});

See it in action here: http://jsfiddle.net/ZUZ3L/g6dMA/

Upvotes: 0

Views: 136

Answers (4)

Faust
Faust

Reputation: 15404

You can save it to the element represented in the DOM with jQuery's .data() function:

Do this on pageLoad:

$(this).data('defaultValue', $(this).val());

You can retrieve it later with:

alert($('#myElement').data('defaultValue');

...which will return the value set at pageload, rather than the current value of the input.

Upvotes: 2

MiniGod
MiniGod

Reputation: 3802

Inside your function $("input").val(function() {, this refers to one element from the $("input") query.
Note that $("input") will return a list of elements, even if only one exists. Use .get() to select an element.
You can access defaultValue from $("input").get(0).defaultValue. (assuming you only want one element)

Upvotes: 0

Lian
Lian

Reputation: 2357

Those functions are callback functions. Which means they are run when the event is fired, (from jQuery). So, this in this context is actually up to jQuery to decide.. in which case is the element to which the event is bound.

On a side note, it looks like you are looking for the placeholder attribute (available only in HTML5, but you can find plugins for older browsers)

Upvotes: 0

Yekver
Yekver

Reputation: 5185

Try this:

<input onfocus="if (this.value==this.defaultValue) this.value = '';" onblur="if (this.value=='') this.value = this.defaultValue;" name="search" value="Search">

Upvotes: 0

Related Questions