禁用/启用提交按钮,直到填写完所有表格 [英] Disable/Enable Submit Button until all forms have been filled

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

问题描述

我希望根据表单是否完全填写来禁用/启用表单提交按钮.

I want my form submit button to be disabled/enabled depending on if the form is completely filled.

当输入被填满时,禁用按钮变为启用.效果很好. 但是我想在输入被清空时禁用该按钮.

When the inputs are filled, the disabled button changes to enabled. That works great. But I would like it to disable the button when an input gets emtied.

这是我的脚本:

<script type="text/javascript" language="javascript">
    function checkform()
    {
        var f = document.forms["theform"].elements;
        var cansubmit = true;

        for (var i = 0; i < f.length; i++) {
            if (f[i].value.length == 0) cansubmit = false;
        }

        if (cansubmit) {
            document.getElementById('submitbutton').disabled = false;
        }
    }
</script> 
<form name="theform">
<input type="text" onKeyup="checkform()" />
<input type="text" onKeyup="checkform()" />
<input id="submitbutton" type="submit" disabled="disabled" value="Submit" />
</form>

推荐答案

只需使用

document.getElementById('submitbutton').disabled = !cansubmit;

代替仅单向工作的if子句.

instead of the the if-clause that works only one-way.

此外,对于禁用了JS的用户,我建议仅通过JS设置初始disabled.为此,只需将脚本移到<form>后面并调用checkform();一次即可.

Also, for the users who have JS disabled, I'd suggest to set the initial disabled by JS only. To do so, just move the script behind the <form> and call checkform(); once.

这篇关于禁用/启用提交按钮,直到填写完所有表格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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