2

I don't remember why i use this.defaultValue ? this.defaultValue : '': in the code below, istead of only this.defaultValue.

$('input:text, textarea').blur(function() {
if ($.trim(this.value) == ''){
this.value = (this.defaultValue ? this.defaultValue : '');
}
});

Why not this:

$('input:text, textarea').blur(function() {
if ($.trim(this.value) == ''){
this.value = this.defaultValue;
}
});

3 Answers 3

1

Because if defaultValue is not defined, you'll get 'undefined' instead of ''

Sign up to request clarification or add additional context in comments.

Comments

1

It's a security. In case this.defaultValue is undefined, it returns an empty string, avoiding this.value to receive undefined.

The thing is that this property is only available for <input>´ and`, pretty much limiting the scope of such a feature. It's pretty common to have selects in a form for instance.

A more straightforward approach would be to use store the default values in a "data-" attribute. It's an HTML5 feature but it has a sort-of backward compatibility as they are just html attributes.

<select data-defaultValue="1">
    <option value="1">One</option>
    <option value="2">Two</option>
</select>

And you can access the attribute with:

$('select').attr('data-defaultValue');
// or
$('select').data('defaultValue');

More info:

Comments

0

On a related note, why not use HTML5's placeholder attribute- you don't have to play around with defaultValue. http://www.w3schools.com/html5/att_input_placeholder.asp

It is not supported on IE as far as I know, but works well on others

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.