93

I have the following code:

var inp = $("#txt");

if(inp.val() != "")
// do something

Is there any other way to check for empty textbox using the variable 'inp'

KJai
  • 1,655
  • 3
  • 15
  • 16

8 Answers8

181
if (inp.val().length > 0) {
    // do something
}

if you want anything more complicated, consider regex or use the validation plugin which takes care of this for you

wiifm
  • 3,787
  • 1
  • 21
  • 23
98
var inp = $("#txt").val();
if(jQuery.trim(inp).length > 0)
{
   //do something
}

Removes white space before checking. If the user entered only spaces then this will still work.

Grimmy
  • 1,173
  • 8
  • 5
17
if ( $("#txt").val().length > 0 )
{
  // do something
}

Your method fails when there is more than 1 space character inside the textbox.

rahul
  • 184,426
  • 49
  • 232
  • 263
8

Use the following to check if text box is empty or have more than 1 white spaces

var name = jQuery.trim($("#ContactUsName").val());

if ((name.length == 0))
{
    Your code 
}
else
{
    Your code
}
Nunser
  • 4,512
  • 8
  • 25
  • 37
KAPIL SHARMA
  • 609
  • 7
  • 4
7
$('input:text').filter(function() { return this.value.length > 0; });
Echilon
  • 10,064
  • 33
  • 131
  • 217
Tod
  • 2,070
  • 21
  • 27
5
if ( $("#txt").val().length == 0 )
{
  // do something
}

I had to add in the == to get it to work for me, otherwise it ignored the condition even with empty text input. May help someone.

4

Also You can use

$value = $("#txt").val();

if($value == "")
{
    //Your Code Here
}
else
{
   //Your code
}

Try it. It work.

Software Engineer
  • 290
  • 1
  • 3
  • 14
4

The check can be done like this:

if (!!inp.val()) {

}

and even shorter:

if (inp.val()) {

}
simhumileco
  • 31,877
  • 16
  • 137
  • 115