禁用提交按钮,直到所有字段都具有值 [英] Disabling submit button until all fields have values

查看:94
本文介绍了禁用提交按钮,直到所有字段都具有值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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>

推荐答案

查看此 jsfiddle .

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

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
        }
    });
})()

有趣的是,表单中有多少输入字段都没有关系,如果至少有1个为空,它将始终使按钮保持禁用状态.它还会检查 .keyup() 上的空度,我认为这样做更便于使用.

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.

这篇关于禁用提交按钮,直到所有字段都具有值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆