Linas
Linas

Reputation: 4408

Checking if input value is not empty or default

I'm look for an elegant way to check if input value is not empty and not default.

For example let's say we have input with value Username, this is a default value, and once the user clicks on this input field Username would be deleted so user could enter what he wants. Just to make it clear this is how it would look when the page is loaded:

<input type="text" class="defaultValue" value="Username" />

Now by default this field would never be empty, unless user would do something to make it empty, so just to make sure i need to check for both things. The way i would do this is very simple:

if($(".defaultValue").val().length == 0 || $(".defaultValue").val() == "Username")
   alert("Please enter your username");

So this works, but looks ugly as hell. And usually i need to deal with huge forms so my code gets really ugly and hard to manage because of this, any way to improve this?

Thanks.

Upvotes: 7

Views: 52255

Answers (2)

Amy
Amy

Reputation: 7466

Try writing a helper function to do this check for you.

var isEmptyOrDefault = function(field, default) {
    var value = $(field).val();
    return (value.length === 0 || value === default);
};

So you can use it:

if (isEmptyOrDefault($('.defaultValue'), 'Username')) {
    alert("Please enter your username");
}

Upvotes: 4

RobG
RobG

Reputation: 147413

Try:

if (this.value == '' || this.value == this.defaultValue) {
  // value is empty or is default value
}

Upvotes: 18

Related Questions