Max Pain
Max Pain

Reputation: 1237

Disable input type submit when input text is empty

I have this code:

setInterval(function(){
  if($("#username_error").val() == "" && $("#password_error").val() == "" && $("#email_error").val() == ""){
    $('input[type="submit"]').removeAttr('disabled');
  } else {
    $('input[type="submit"]').attr('disabled','disabled');
  }
}, 10);

I need to disable the submit button if there are no errors for three divs. When I run this code, nothing happens. But if I do an alert() this if statement runs correctly. What am I doing wrong here?

Upvotes: 0

Views: 813

Answers (3)

Adriano Silva
Adriano Silva

Reputation: 2576

Another solution...

$(document).ready(function () {
    $('button').attr("disabled", true); // starts disabling the button
    $('input').on("blur", null, function () {
        if ($("#username_error").val() != "" && $("#password_error").val() != "" && $("#email_error").val() != "") {
            $("#botao").attr("disabled", false);
        } else {
            $("#botao").attr("disabled", true);
        }
    });
});

Upvotes: 0

Arvind Bhardwaj
Arvind Bhardwaj

Reputation: 5291

Do it like:

$('input[type="submit"]').attr('disabled','disabled');    

$('input[type="text"]').change(function(){
   if($("#username_error").val() == "" && $("#password_error").val() == "" && $("#email_error").val() == "") {
       $('input[type="submit"]').removeAttr('disabled');
   } else {
       $('input[type="submit"]').attr('disabled','disabled');
   }
});

DEMO

Upvotes: 1

Anoop
Anoop

Reputation: 23208

Use jQuery keyup event.

$('input').keyup(function(){
       if($("#username_error").val() == "" && $("#password_error").val() == "" && $("#email_error").val() == "") {
         $('input[type="submit"]').attr('disabled',true);
       } else {
         $('input[type="submit"]').attr('disabled', false);
       }
    });

Upvotes: 0

Related Questions