Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 237
Linas Avatar asked Mar 06 '13 22:03

Linas


2 Answers

Try:

if (this.value == '' || this.value == this.defaultValue) {
  // value is empty or is default value
}
like image 188
RobG Avatar answered Oct 29 '22 01:10

RobG


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");
}
like image 4
Amy Avatar answered Oct 28 '22 23:10

Amy