jQuery form input defaultValue

When creating a form to accept user info, there are times when functions related to a form input's default value are required. For example, you have a field that says "search here", and when the user clicks in the field, the default value is removed so the user can begin typing. But, if the user leaves the field blank, you might want that default term to return. In regular javascript, we use something like this:


if(inputName.value == ''){
inputName.value = inputName.defaultValue
};

but jQuery doesn't have a built-in method for retrieving that default value. Thankfully, google found me a super easy workaround - this discussion thread holds the key:


if ($(this).val() == "") {
var defVal = $(this)[0].defaultValue;
$(this).val(defVal);
}

Note the [0] in the defaultValue. As explained in the thread linked above: "If you imagine $(this) as an array of DOM objects within jQuery, then $(this)[0] is a way to access the first (or in this case, only) DOM object. jQuery doesn't have a built in way to retrieve the default value of an input, so we have to nip back into the DOM momentarily in order to retrieve it. "

Comments (Comment Moderation is enabled. Your comment will not appear until approved.)
This is exactly what I was looking for, thanks. I was surprised to find that jQuery doesn't have a built in method for retrieving the default form value but, as you show, getting the value from the DOM is easy enough.
# Author Matthew | 3/7/11 9:38 AM
Since you are utilizing a default javascript functionality, an alternate way to do this would be as follows:

if ($(this).val() == "") {
$(this).val(this.defaultValue);
}

The object "this" is actually a direct javascript object that when placed into the jQuery call, $(), simply associates that object with the DOM item. So you can just straight-up grab the items defaultValue.
# Author Aaron | 4/14/11 6:32 PM
Actually, this is much more useful than seen at face value when used for other applications. For example, when I wanted to use jQuery's data feature to apply information to an element I had created, I experienced problems:

var e = $('<span />').text('Who is John Galt?');
$.data(e, 'answer', 42);

This does not work, as $.data() accepts a DOM element, not a jQuery object. Your solution works perfectly:

$.data(e[0], 'answer', 42);
# Author John Galt | 6/14/11 7:23 PM
Very helpful thank you.

I was trying to do $('#value').defaultValue = 'blah'
but doing what you said fixed my problem $('#value')[0].defaultValue = 'blah'
# Author John | 8/31/11 8:33 PM
blogcfc 5.9.1.002 by raymond camden
contact michael evangelista