HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptCritical

jQuery disable/enable submit button

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
disablesubmitjquerybuttonenable

Problem

I have this HTML:



How can I do something like this:

  • When the text field is empty the submit should be disabled (disabled="disabled").



  • When something is typed in the text field to remove the disabled attribute.



  • If the text field becomes empty again(the text is deleted) the submit button should be disabled again.



I tried something like this:

$(document).ready(function(){
    $('input[type="submit"]').attr('disabled','disabled');
    $('input[type="text"]').change(function(){
        if($(this).val != ''){
            $('input[type="submit"]').removeAttr('disabled');
        }
    });
});


…but it doesn't work. Any ideas?

Solution

The problem is that the change event fires only when focus is moved away from the input (e.g. someone clicks off the input or tabs out of it). Try using keyup instead:

$(document).ready(function() {
     $(':input[type="submit"]').prop('disabled', true);
     $('input[type="text"]').keyup(function() {
        if($(this).val() != '') {
           $(':input[type="submit"]').prop('disabled', false);
        }
     });
 });

Code Snippets

$(document).ready(function() {
     $(':input[type="submit"]').prop('disabled', true);
     $('input[type="text"]').keyup(function() {
        if($(this).val() != '') {
           $(':input[type="submit"]').prop('disabled', false);
        }
     });
 });

Context

Stack Overflow Q#1594952, score: 1441

Revisions (0)

No revisions yet.