Saulius Slavinskas Saulius Slavinskas - 11 days ago 7
jQuery Question

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);
}
})
});

Answer

You are disabling only on document.ready and this happens only once when DOM is ready but you need to disable in keyup event too when textbox gets empty. Also change $(this).val.length to $(this).val().length

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

Or you can use conditional operator instead of if statement. also use prop instead of attr as attribute is not recommended by jQuery 1.6 and above for disabled, checked etc.

As of jQuery 1.6, the .attr() method returns undefined for attributes that have not been set. To retrieve and change DOM properties such as the checked, selected, or disabled state of form elements, use the .prop() method, jQuery docs

$(document).ready(function(){
    $('.sendButton').prop('disabled',true);
    $('#message').keyup(function(){
        $('.sendButton').prop('disabled', this.value == "" ? true : false);     
    })
});