jQuery 如果输入字段为空,则禁用提交按钮

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17699094/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 19:46:45  来源:igfitidea点击:

If input field is empty, disable submit button

jqueryforms

提问by Saulius s

I'm trying to disable submit button if the user hasn't provided any text.

如果用户未提供任何文本,我将尝试禁用提交按钮。

At first sight it looks that everything works just fine, but if user types some text, then deletes it, the submit button becomes enabled.

乍一看,一切正常,但如果用户键入一些文本,然后将其删除,则提交按钮将启用。

Here is my code:

这是我的代码:

$(document).ready(function(){
    $('.sendButton').attr('disabled',true);
    $('#message').keyup(function(){
        if($(this).val.length !=0){
            $('.sendButton').attr('disabled', false);
        }
    })
});

回答by Adil

You are disabling only on document.readyand this happens only once when DOMis ready but you need to disablein keyup event too when textbox gets empty. Also change $(this).val.lengthto $(this).val().length

您仅禁用 ondocument.ready并且这仅在DOM准备好时发生一次,但是disable当文本框变空时您也需要在 keyup 事件中。也$(this).val.length改为$(this).val().length

$(document).ready(function(){
    $('.sendButton').attr('disabled',true);
    $('#message').keyup(function(){
        if($(this).val().length !=0)
            $('.sendButton').attr('disabled', false);            
        else
            $('.sendButton').attr('disabled',true);
    })
});

Or you can use conditional operator instead of if statement. also use prop instead of attras attribute is not recommended by jQuery 1.6and above for disabled, checked etc.

或者您可以使用条件运算符而不是 if 语句。还使用prop 而不是 attr因为jQuery 1.6及更高版本不推荐用于禁用、检查等的属性。

As of jQuery 1.6, the .attr() method returns undefined for attributes that have not been set. To retrieve and change DOM properties such as the checked, selected, or disabled state of form elements, use the .prop()method, jQuery docs

从 jQuery 1.6 开始,.attr() 方法为尚未设置的属性返回 undefined。要检索和更改 DOM 属性,例如表单元素的选中、选中或禁用状态,请使用 .prop()方法,jQuery 文档

$(document).ready(function(){
    $('.sendButton').prop('disabled',true);
    $('#message').keyup(function(){
        $('.sendButton').prop('disabled', this.value == "" ? true : false);     
    })
});  

回答by Nalaka526

Try this code

试试这个代码

$(document).ready(function(){
    $('.sendButton').attr('disabled',true);

    $('#message').keyup(function(){
        if($(this).val().length !=0){
            $('.sendButton').attr('disabled', false);
        }
        else
        {
            $('.sendButton').attr('disabled', true);        
        }
    })
});

Check demo Fiddle

检查演示小提琴

You are missing the else part of the if statement (to disable the button again if textbox is empty) and parentheses ()after valfunction in if($(this).val.length !=0){

这是因为丢失的if语句的其他部分(禁用按钮,如果再次文本框为空)和括号()val的功能 if($(this).val.length !=0){

回答by Akbar

Please try this

请试试这个

<!DOCTYPE html>
<html>
  <head>
    <title>Jquery</title>
    <meta charset="utf-8">       
    <script src='http://code.jquery.com/jquery-1.7.1.min.js'></script>
  </head>

  <body>

    <input type="text" id="message" value="" />
    <input type="button" id="sendButton" value="Send">

    <script>
    $(document).ready(function(){  

      var checkField;

      //checking the length of the value of message and assigning to a variable(checkField) on load
      checkField = $("input#message").val().length;  

      var enableDisableButton = function(){         
        if(checkField > 0){
          $('#sendButton').removeAttr("disabled");
        } 
        else {
          $('#sendButton').attr("disabled","disabled");
        }
      }        

      //calling enableDisableButton() function on load
      enableDisableButton();            

      $('input#message').keyup(function(){ 
        //checking the length of the value of message and assigning to the variable(checkField) on keyup
        checkField = $("input#message").val().length;
        //calling enableDisableButton() function on keyup
        enableDisableButton();
      });
    });
    </script>
  </body>
</html>

回答by Marcelo Machado

An easy way to do:

一个简单的方法:

function toggleButton(ref,bttnID){
    document.getElementById(bttnID).disabled= ((ref.value !== ref.defaultValue) ? false : true);
}


<input ... onkeyup="toggleButton(this,'bttnsubmit');">
<input ... disabled='disabled' id='bttnsubmit' ... >

回答by jkras

For those that use coffeescript, I've put the code we use globally to disable the submit buttons on our most widely used form. An adaption of Adil's answer above.

对于那些使用coffeescript 的人,我已经将我们在全局使用的代码放在我们最广泛使用的表单上以禁用提交按钮。对上述 Adil 回答的改编。

$('#new_post button').prop 'disabled', true
$('#new_post #post_message').keyup ->
    $('#new_post button').prop 'disabled', if @value == '' then true else false
    return