Check if textbox has empty value

后端 未结 8 2031
感情败类
感情败类 2020-11-30 23:19

I have the following code:

var inp = $(\"#txt\");

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

Is there any other way to check for empty textbox

相关标签:
8条回答
  • 2020-11-30 23:44
    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.

    0 讨论(0)
  • 2020-11-30 23:45
    if ( $("#txt").val().length > 0 )
    {
      // do something
    }
    

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

    0 讨论(0)
  • 2020-11-30 23:53
    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

    0 讨论(0)
  • 2020-11-30 23:53
    $('input:text').filter(function() { return this.value.length > 0; });
    
    0 讨论(0)
  • 2020-11-30 23:56

    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
    }
    
    0 讨论(0)
  • 2020-11-30 23:58
    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.

    0 讨论(0)
提交回复
热议问题