javascript tutorial - [Solved-5 Solutions] jQuery disable/enable submit button - javascript - java script - javascript array



Problem:

We have this html:

<input type="text" name="textField" />
<input type="submit" value="send" />
click below button to copy the code. By JavaScript tutorial team

How can we 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.

We 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');
        }
    });
});
click below button to copy the code. By JavaScript tutorial team

... but it doesn't work. Any ideas? Thanks.

Solution 1:

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);
        }
     });
 });
click below button to copy the code. By JavaScript tutorial team

Solution 2:

	$(function() {
  $(":text").keypress(check_submit).each(function() {
    check_submit();
  });
});

function check_submit() {
  if ($(this).val().length == 0) {
    $(":submit").attr("disabled", true);
  } else {
    $(":submit").removeAttr("disabled");
  }
}
click below button to copy the code. By JavaScript tutorial team

Solution 3:

or for us that dont like to use jQ for every little thing:

document.getElementById("submitButtonId").disabled = true;
click below button to copy the code. By JavaScript tutorial team

Solution 4:

eric, our code did not seem to work for me when the user enters text then deletes all the text. we created another version if anyone experienced the same problem. here ya go folks:

$('input[type="submit"]').attr('disabled','disabled');
$('input[type="text"]').keyup(function(){
    if($('input[type="text"]').val() == ""){
        $('input[type="submit"]').attr('disabled','disabled');
    }
    else{
        $('input[type="submit"]').removeAttr('disabled');
    }
})
click below button to copy the code. By JavaScript tutorial team

Solution 5:

To remove disabled attribute use,

 $("#elementID").removeAttr('disabled');
click below button to copy the code. By JavaScript tutorial team

and to add disabled attribute use,

$("#elementID").prop("disabled", true);

click below button to copy the code. By JavaScript tutorial team

Related Searches to javascript tutorial - jQuery disable/enable submit button