Check if textbox has empty value

Jquery

Jquery Problem Overview


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'

Jquery Solutions


Solution 1 - Jquery

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

Solution 2 - Jquery

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.

Solution 3 - Jquery

if ( $("#txt").val().length > 0 )
{
  // do something
}

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

Solution 4 - Jquery

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
}

Solution 5 - Jquery

$('input:text').filter(function() { return this.value.length > 0; });

Solution 6 - Jquery

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.

Solution 7 - Jquery

Also You can use

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

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

Try it. It work.

Solution 8 - Jquery

The check can be done like this:

if (!!inp.val()) {

}

and even shorter:

if (inp.val()) {

}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionKJaiView Question on Stackoverflow
Solution 1 - JquerywiifmView Answer on Stackoverflow
Solution 2 - JqueryGrimmyView Answer on Stackoverflow
Solution 3 - JqueryrahulView Answer on Stackoverflow
Solution 4 - JqueryKAPIL SHARMAView Answer on Stackoverflow
Solution 5 - JqueryTodView Answer on Stackoverflow
Solution 6 - JqueryRicky Odin MatthewsView Answer on Stackoverflow
Solution 7 - JquerySoftware EngineerView Answer on Stackoverflow
Solution 8 - JquerysimhumilecoView Answer on Stackoverflow