[jquery] If input field is empty, disable submit button

I'm trying to disable submit button if the user hasn't provided any text.

At first sight it looks that everything works just fine, but if user types some text, then deletes it, the submit button becomes enabled.

Here is my code:

$(document).ready(function(){
    $('.sendButton').attr('disabled',true);
    $('#message').keyup(function(){
        if($(this).val.length !=0){
            $('.sendButton').attr('disabled', false);
        }
    })
});

This question is related to jquery forms

The answer is


For those that use coffeescript, I've put the code we use globally to disable the submit buttons on our most widely used form. An adaption of Adil's answer above.

$('#new_post button').prop 'disabled', true
$('#new_post #post_message').keyup ->
    $('#new_post button').prop 'disabled', if @value == '' then true else false
    return

Please try this

<!DOCTYPE html>
<html>
  <head>
    <title>Jquery</title>
    <meta charset="utf-8">       
    <script src='http://code.jquery.com/jquery-1.7.1.min.js'></script>
  </head>

  <body>

    <input type="text" id="message" value="" />
    <input type="button" id="sendButton" value="Send">

    <script>
    $(document).ready(function(){  

      var checkField;

      //checking the length of the value of message and assigning to a variable(checkField) on load
      checkField = $("input#message").val().length;  

      var enableDisableButton = function(){         
        if(checkField > 0){
          $('#sendButton').removeAttr("disabled");
        } 
        else {
          $('#sendButton').attr("disabled","disabled");
        }
      }        

      //calling enableDisableButton() function on load
      enableDisableButton();            

      $('input#message').keyup(function(){ 
        //checking the length of the value of message and assigning to the variable(checkField) on keyup
        checkField = $("input#message").val().length;
        //calling enableDisableButton() function on keyup
        enableDisableButton();
      });
    });
    </script>
  </body>
</html>

Try this code

$(document).ready(function(){
    $('.sendButton').attr('disabled',true);

    $('#message').keyup(function(){
        if($(this).val().length !=0){
            $('.sendButton').attr('disabled', false);
        }
        else
        {
            $('.sendButton').attr('disabled', true);        
        }
    })
});

Check demo Fiddle

You are missing the else part of the if statement (to disable the button again if textbox is empty) and parentheses () after val function in if($(this).val.length !=0){


An easy way to do:

function toggleButton(ref,bttnID){
    document.getElementById(bttnID).disabled= ((ref.value !== ref.defaultValue) ? false : true);
}


<input ... onkeyup="toggleButton(this,'bttnsubmit');">
<input ... disabled='disabled' id='bttnsubmit' ... >