jQuery禁用/启用提交按钮

JavaScript

番长斯丁Itachi

2020-03-10

我有这个HTML:

<input type="text" name="textField" />
<input type="submit" value="send" />

我该如何做这样的事情:

  • 当文本字段为空时,应禁用提交(disabled =“ disabled”)。
  • 在文本字段中键入内容以删除禁用的属性时。
  • 如果文本字段再次变为空(删除了文本),则应再次禁用提交按钮。

我尝试过这样的事情:

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

…但这不起作用。有任何想法吗?

第508篇《jQuery禁用/启用提交按钮》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

3个回答
Eva猿 2020.03.10

If the button is itself a jQuery styled button (with .button()) you will need to refresh the state of the button so that the correct classes are added / removed once you have removed/added the disabled attribute.

$( ".selector" ).button( "refresh" );
理查德村村小宇宙 2020.03.10

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

document.getElementById("submitButtonId").disabled = true;
Tony阳光 2020.03.10
$(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");
  }
}

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android