简体   繁体   English

保持提交按钮处于禁用状态,直到表单字段填满

[英]Keeping Submit Button Disabled Until Form Fields Are Full

Would someone be able to take a look at my code and see what I'm missing here? 有人可以看一下我的代码,看看我在这里缺少什么吗?

I have a multi-page form with quite a lot of inputs, and I would like to keep "next page" buttons and the final "submit" buttons disabled until all the fields are full. 我有一个包含大量输入的多页表单,并且我希望禁用“下一页”按钮和最后的“提交”按钮,直到所有字段都填满为止。

I am trying to recreate the process on a smaller scale but in my tests, I cannot seem to re-enable the disabled submit input. 我试图以较小的比例重新创建该过程,但是在我的测试中,我似乎无法重新启用禁用的提交输入。 I've checked the console and the JS is logging the variable elements so I'm not sure what I'm missing. 我已经检查了控制台,并且JS正在记录变量元素,所以我不确定我缺少什么。

 function checkForm() { var elements = document.forms[0].elements; var cansubmit= true; for(var i = 0; i < elements.length; i++) { if(elements[i].value.length == 0 || elements[i].value.length == "" || elements[i].value.length == null) { cansubmit = false; } document.getElementById("myButton").disabled = !cansubmit; } }; 
 <form> <label for="firstName">First Name:</label> <input type="text" id="firstName" onkeyup="checkForm()" /> <br /> <label for="lastName">Last Name:</label> <input type="text" id="lastName" onkeyup="checkForm()" /> <button type="button" id="myButton" disabled="disabled">Test me</button> </form> 

Your elements array includes your button , which has no value. 您的elements数组包含没有价值的button This will cause your loop to always evaluate to cansubmit = false; 这将导致您的循环始终求值为cansubmit = false; .

Try this instead: https://jsfiddle.net/e00sorLu/2/ 请尝试以下方法: https : //jsfiddle.net/e00sorLu/2/

function checkForm()
{
    var elements = document.forms[0].elements;

    var cansubmit= true;
    for(var i = 0; i < elements.length; i++)
    {
        if(elements[i].value.length == 0 && elements[i].type != "button")
        {
            cansubmit = false;
        }

    }

    document.getElementById("myButton").disabled = !cansubmit;  
};

Answer was already accepted, but here are a few other things you might consider: 答案已被接受,但是您可能需要考虑以下其他事项:

The way you have it set up now, for absolutely anything other than an empty string "" you're setting button.disabled = false and enabling the button. 现在设置的方式,除了空字符串""您还可以设置button.disabled = false并启用该按钮。

  1. You're checking value.length 3 times, but you actually want to check .value instead. 您正在检查value.length 3次,但实际上您想检查.value The length property is only a numeric value for how many code units are in the string - it won't ever be "" or null , so the only thing you're really checking is the very first condition for an empty string of length 0. length属性只是一个数字 ,表示字符串中有多少个代码单元-永远不会是""null ,因此您真正要检查的唯一条件是长度为0的空字符串的第一个条件。

    You're also not accounting for multiple white spaces in a blank string, so " " would be valid) ... or special characters, so this would be valid: (function goodByeWorld(evil){//do the bad things})(); 您也没有考虑空白字符串中的多个空格,因此" "将是有效的)...或特殊字符,因此这将是有效的:( (function goodByeWorld(evil){//do the bad things})();

  2. You're running the checkForm() function on all form elements (including the <button> ) after every single keystroke. 每次击键后,都在所有表单元素(包括<button> )上运行checkForm()函数。 This is unnecessary. 这是不必要的。

    Aside from including <button> , which was pointed out in the accepted answer & will always cause this to fail, you should either validate each individual form element with inline error checking (preferable), or validate all of them once just prior to submission (preferable to server-side validation & kicking it back after submission). 除了包含<button> (在接受的答案中已指出并会导致此操作失败)之外,您还应该使用内联错误检查(优选)来验证每个单独的表单元素,或者在提交之前对所有这些元素进行一次验证(优于服务器端验证,并在提交后将其踢回)。

    You could bind to onblur() instead and send the current element's value as an argument once that field loses focus. 您可以绑定到onblur()并在该字段失去焦点后将当前元素的值作为参数发送。 eg change to: function checkValue(value) {//validate the value} ) and either onblur = checkValue(this) in the HTML or preferably a non-inline event handler that lives in the JS file instead. 例如,更改为: function checkValue(value) {//validate the value} ),或者HTML中的onblur = checkValue(this)或最好是onblur = checkValue(this)在JS文件中的非内联事件处理程序。

    You could still do it onkeyup = checkValue(this) to check after every keystroke, but change the function to only check 1 element instead of checking theentireform dozens of times. 您仍然可以在每次击键之后执行onkeyup = checkValue(this)进行检查,但是将功能更改为仅检查1个元素,而不是多次检查整个改革。

    This approach would let you individually keep track of each separate form element's validity (lots of options here depending on what "valid" means - store an array of values, objects with values or "valid/invalid" flags, etc, switch on the field labels to validate this for different types of information). 这种方法可以让您单独跟踪每个单独的表单元素的有效性(此处的许多选项取决于“有效”的含义-存储值的数组,带有值的对象或“有效/无效”标志等,打开该字段标签以针对不同类型的信息this进行验证)。 You can run additional validation on the individual elements as well (eg min/max name length, eliminating special characters, etc), and display real-time error checking messages next to each form element. 您还可以对单个元素运行附加验证(例如,最小/最大名称长度,消除特殊字符等),并在每个表单元素旁边显示实时错误检查消息。

  3. You're defaulting to cansubmit = true which doesn't make much sense, given what you intend for this code to do. 鉴于您打算将此代码执行的工作,因此您默认情况下默认为cansubmit = true ,这没有多大意义。 Using !cansubmit only serves to confuse yourself & others reading the code. 使用!cansubmit只会使您自己和其他人混淆阅读代码。 For readability, consider inverting it to disableSubmit so it's in sync with the button.disabled state, which should only be true or false . 为了提高可读性,请考虑将其反转为disableSubmit以便它与button.disabled状态保持同步,该状态只能为truefalse

Or you can use jQuery. 或者您可以使用jQuery。

    <script type="text/javascript">
        function checkForm() {
            var cansubmit = false;
            $('form input[type="text"]').each(function (index, element) {
                if (element.value == "") {
                    cansubmit = true;
                }
            });
            document.getElementById("myButton").disabled = cansubmit;
        }
    </script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM