jQuery 禁用提交按钮,直到所有字段都有值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5614399/
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:29:38  来源:igfitidea点击:

Disabling submit button until all fields have values

jquery

提问by AndrewFerrara

I want to disable my submit button until all the fields have values.. how can I do that?

我想禁用我的提交按钮,直到所有字段都有值。我该怎么做?

<html>
    <head>
        <title></title>
        <style type="text/css">
        </style>
        <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script>
        <script type="text/javascript">
        $(document).ready(function() {
            $('#register').attr("disabled", true);
        });
        </script>
    </head>
    <body>
        <form>
        Username<br />
        <input type="text" id="user_input" name="username" /><br />
        Password<br />
        <input type="text" id="pass_input" name="password" /><br />
        Confirm Password<br />
        <input type="text" id="v_pass_input" name="v_password" /><br />
        Email<br />
        <input type="text" id="email" name="email" /><br />     
        <input type="submit" id="register" value="Register" />
        </form>
        <div id="test">
        </div>
    </body>
</html>

回答by Hristo

Check out this jsfiddle.

看看这个jsfiddle

HTML

HTML

// note the change... I set the disabled property right away
<input type="submit" id="register" value="Register" disabled="disabled" />

JavaScript

JavaScript

(function() {
    $('form > input').keyup(function() {

        var empty = false;
        $('form > input').each(function() {
            if ($(this).val() == '') {
                empty = true;
            }
        });

        if (empty) {
            $('#register').attr('disabled', 'disabled'); // updated according to http://stackoverflow.com/questions/7637790/how-to-remove-disabled-attribute-with-jquery-ie
        } else {
            $('#register').removeAttr('disabled'); // updated according to http://stackoverflow.com/questions/7637790/how-to-remove-disabled-attribute-with-jquery-ie
        }
    });
})()

The nice thing about this is that it doesn't matter how many input fields you have in your form, it will always keep the button disabled if there is at least 1 that is empty. It also checks emptiness on the .keyup()which I think makes it more convenient for usability.

这样做的好处是,您的表单中有多少个输入字段并不重要,如果至少有 1 个为空,它会始终禁用按钮。它还检查空性.keyup(),我认为这使可用性更方便。

回答by rsplak

$('#user_input, #pass_input, #v_pass_input, #email').bind('keyup', function() {
    if(allFilled()) $('#register').removeAttr('disabled');
});

function allFilled() {
    var filled = true;
    $('body input').each(function() {
        if($(this).val() == '') filled = false;
    });
    return filled;
}

JSFiddle with your code, works :)

JSFiddle 与您的代码,有效:)

回答by Sashank

For all solutions instead of ".keyup" ".change" should be used or else the submit button wont be disabled when someone just selects data stored in cookies for any of the text fields.

对于所有解决方案,应该使用“.keyup”而不是“.change”,否则当有人只是为任何文本字段选择存储在 cookie 中的数据时,提交按钮不会被禁用。

回答by Hussein

All variables are cached so the loop and keyup event doesn't have to create a jQuery object everytime it runs.

所有变量都被缓存,因此循环和 keyup 事件不必每次运行时都创建一个 jQuery 对象。

var $input = $('input:text'),
    $register = $('#register');    
$register.attr('disabled', true);

$input.keyup(function() {
    var trigger = false;
    $input.each(function() {
        if (!$(this).val()) {
            trigger = true;
        }
    });
    trigger ? $register.attr('disabled', true) : $register.removeAttr('disabled');
});

Check working example at http://jsfiddle.net/DKNhx/3/

http://jsfiddle.net/DKNhx/3/检查工作示例

回答by fl00r

DEMO: http://jsfiddle.net/kF2uK/2/

演示:http: //jsfiddle.net/kF2uK/2/

function buttonState(){
    $("input").each(function(){
        $('#register').attr('disabled', 'disabled');
        if($(this).val() == "" ) return false;
        $('#register').attr('disabled', '');
    })
}

$(function(){
    $('#register').attr('disabled', 'disabled');
    $('input').change(buttonState);
})

回答by J Grover

I refactored the chosen answer here and improved on it. The chosen answer only works assuming you have one form per page. I solved this for multiple forms on same page (in my case I have 2 modals on same page) and my solution only checks for values on required fields. My solution gracefully degrades if JavaScript is disabled and includes a slick CSS button fade transition.

我在这里重构了选择的答案并对其进行了改进。所选答案仅在您每页有一个表格的情况下有效。我为同一页面上的多个表单解决了这个问题(在我的情况下,我在同一页面上有 2 个模式),我的解决方案只检查必填字段上的值。如果 JavaScript 被禁用并包含一个光滑的 CSS 按钮淡入淡出过渡,我的解决方案会优雅地降级。

See working JS fiddle example: https://jsfiddle.net/bno08c44/4/

请参阅工作 JS 小提琴示例:https: //jsfiddle.net/bno08c44/4/

JS

JS

$(function(){
 function submitState(el) {

    var $form = $(el),
        $requiredInputs = $form.find('input:required'),
        $submit = $form.find('input[type="submit"]');

    $submit.attr('disabled', 'disabled');

    $requiredInputs.keyup(function () {

      $form.data('empty', 'false');

      $requiredInputs.each(function() {
        if ($(this).val() === '') {
          $form.data('empty', 'true');
        }
      });

      if ($form.data('empty') === 'true') {
        $submit.attr('disabled', 'disabled').attr('title', 'fill in all required fields');
      } else {
        $submit.removeAttr('disabled').attr('title', 'click to submit');
      }
    });
  }

  // apply to each form element individually
  submitState('#sign_up_user');
  submitState('#login_user');
});

CSS

CSS

input[type="submit"] {
  background: #5cb85c;
  color: #fff;
  transition: background 600ms;
  cursor: pointer;
}

input[type="submit"]:disabled {
  background: #555;
  cursor: not-allowed;
}

HTML

HTML

<h4>Sign Up</h4>
<form id="sign_up_user" data-empty="" action="#" method="post">
 <input type="email" name="email" placeholder="Email" required>
 <input type="password" name="password" placeholder="Password" required>
 <input type="password" name="password_confirmation" placeholder="Password Confirmation" required>
 <input type="hidden" name="secret" value="secret">
 <input type="submit" value="signup">
</form>

<h4>Login</h4>
<form id="login_user" data-empty="" action="#" method="post">
 <input type="email" name="email" placeholder="Email" required>
 <input type="password" name="password" placeholder="Password" required>
 <input type="checkbox" name="remember" value="1"> remember me
 <input type="submit" value="signup">
</form>

回答by CSquared

Built upon rsplak's answer. It uses jQuery's newer .on()instead of the deprecated .bind(). In addition to input, it will also work for select and other html elements. It will also disable the submit button if one of the fields becomes blank again.

基于rsplak的答案。它使用 jQuery 较新的.on()而不是已弃用的.bind()。除了输入,它还适用于 select 和其他 html 元素。如果其中一个字段再次变为空白,它也会禁用提交按钮。

var fields = "#user_input, #pass_input, #v_pass_input, #email";

$(fields).on('change', function() {
    if (allFilled()) {
        $('#register').removeAttr('disabled');
    } else {
        $('#register').attr('disabled', 'disabled');
    }
});

function allFilled() {
    var filled = true;
    $(fields).each(function() {
        if ($(this).val() == '') {
            filled = false;
        }
    });
    return filled;
}

Demo: JSFiddle

演示:JSFiddle

回答by Andrew

This works well since all the inputs have to meet the condition of not null.

这很有效,因为所有输入都必须满足非空条件。

$(function () {
    $('#submits').attr('disabled', true);
    $('#input_5').change(function () {
        if ($('#input_1').val() != '' && $('#input_2').val() != '' && $('#input_3').val() != '' && $('#input_4').val() != '' && $('#input_5').val() != '') {
            $('#submit').attr('disabled', false);
        } else {
            $('#submit').attr('disabled', true);
        }
     });
 });

回答by Dudo

Grave digging... I like a different approach:

挖坟……我喜欢不同的方法:

elem = $('form')
elem.on('keyup','input', checkStatus)
elem.on('change', 'select', checkStatus)

checkStatus = (e) =>
  elems = $('form').find('input:enabled').not('input[type=hidden]').map(-> $(this).val())
  filled = $.grep(elems, (n) -> n)
  bool = elems.size() != $(filled).size()
  $('input:submit').attr('disabled', bool)