简体   繁体   中英

Disable Form submit button if text field filled in

I am trying to implement some Jquery that basically says "If this text field is filled in then disable the submit button so that the form cannot be delivered/submitted"

So far I have come up with this, but it is not working

$(document).ready(function(){
$this = $("#inputValue");
 if($this.val().length>0){ 
$('input[type=submit]').attr('disabled', 'disabled');
 }  
});

When i fill in the form and include text within the field I am not supposed to the form still gets submitted, what am i doing wrong?

Thanks

Your code only runs once on runtime. After that, it doesn't get checked again.

$(document).ready(function (){
  $("#inputValue").on('change', function (){
    if($(this).val().length > 0){
      $('input[type=submit]').attr('disabled', 'disabled');
    } else {
      $('input[type=submit]').removeAttr('disabled');
    }
  });
});

Or, as @thomasfedb suggested:

$(document).ready(function (){
  $('#inputValue').on('change', function() {
    $("input[type=submit]").prop('disabled', $(this).val().length > 0);
  });
});

I'd suggest you to bind a keyup event to do the check every time when user enters something to #inputValue field:

$(document).ready(function() {
    $("#inputValue").on("keyup", function() {
        $("input[type=submit]").prop("disabled", !!$.trim(this.value).length);
    }).trigger("keyup");
});

Since you're using a hidden field it might be better to bind the change event:

$('#inputValue').on('change', function() {
  $('input[type="submit"]').prop('disabled', this.value.length > 0);
}).change();

尝试使用此代码。

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM