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. "


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.
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);
I was trying to do $('#value').defaultValue = 'blah'
but doing what you said fixed my problem $('#value')[0].defaultValue = 'blah'
You've saved me plenty of hours of frustration staring at an always undefined defaultValue.
Cheers ;)
$('.instructionField').click(function(evt) {
var defVal = $(this)[0].defaultValue;
if (this.value==defVal) { // if field has its original default value
$(this).val(""); // empty the field so user can enter text without having to delete instruction text
}
});
for an input field:
<input name="textfield" type="text" class="instructionField" value="Enter your first name">