【问题标题】:Disable/Enable Submit Button until all forms have been filled禁用/启用提交按钮,直到填写所有表格
【发布时间】:2012-12-05 14:00:17
【问题描述】:

我希望我的表单提交按钮被禁用/启用,具体取决于表单是否已完全填写。

当输入被填满时,禁用的按钮变为启用。这很好用。 但我希望它在输入被清空时禁用按钮。

这是我的脚本:

<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>

【问题讨论】:

    标签: javascript forms submit disabled-control


    【解决方案1】:

    您可以根据下面的javascript验证启用和禁用提交按钮是验证码。

    <script>
    function validate() {
    
    var valid = true;
    valid = checkEmpty($("#name"));
    valid = valid && checkEmail($("#email"));
    
    $("#san-button").attr("disabled",true);
    if(valid) {
    $("#san-button").attr("disabled",false);
    } 
    }
    function checkEmpty(obj) {
    var name = $(obj).attr("name");
    $("."+name+"-validation").html(""); 
    $(obj).css("border","");
    if($(obj).val() == "") {
    $(obj).css("border","#FF0000 1px solid");
    $("."+name+"-validation").html("Required");
    return false;
    }
    
    return true; 
    }
    function checkEmail(obj) {
    var result = true;
    
    var name = $(obj).attr("name");
    $("."+name+"-validation").html(""); 
    $(obj).css("border","");
    
    result = checkEmpty(obj);
    
    if(!result) {
    $(obj).css("border","#FF0000 1px solid");
    $("."+name+"-validation").html("Required");
    return false;
    }
    
    var email_regex = /^([a-zA-Z0-9_.+-])+\@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,3})+$/;
    result = email_regex.test($(obj).val());
    
    if(!result) {
    $(obj).css("border","#FF0000 1px solid");
    $("."+name+"-validation").html("Invalid");
    return false;
    }
    
    return result; 
    }
    </script>  
    

    【讨论】:

      【解决方案2】:

      这是我验证带有禁用按钮的表单的方法。查看下面的 sn-p:

      var inp = document.getElementsByTagName("input");
      var btn = document.getElementById("btn");
      // Disable the button dynamically using javascript
      btn.disabled = "disabled";
      
      function checkForm() {
          for (var i = 0; i < inp.length; i++) {
              if (inp[i].checkValidity() == false) {
                  btn.disabled = "disabled";
              } else {
                  btn.disabled = false;
              }
          }
      }
      <!DOCTYPE html>
      <html lang="en">
      <head>
          <meta charset="UTF-8"/>
          <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
          <title>JavaScript</title>
      </head>
      <body>
      
      <h1>Javascript form validation</h1>
      <p>Javascript constraint form validation example:</p>
      
      <form onkeyup="checkForm()" autocomplete="off" novalidate>
          <input type="text" name="fname" placeholder="First Name" required><br><br>
          <input type="text" name="lname" placeholder="Last Name" required><br><br>
          <button type="submit" id="btn">Submit</button>
      </form>
      
      </body>
      </html>

      示例说明:

      1. 我们创建一个变量来存储所有输入元素。
        var inp = document.getElementsByTagName("input");
        
      2. 我们创建另一个变量来存储按钮元素
        var btn = document.getElementById("btn");
        
      3. 我们循环遍历输入元素的集合
        for (var i = 0; i < inp.length; i++) {
            // Code
        }
        
      4. 最后,我们使用checkValidity()方法检查输入元素是否 (带有required 属性)是否有效(代码插入到 for 循环)。如果无效,则按钮将保持禁用状态,否则 属性被移除。
        for (var i = 0; i < inp.length; i++) {
            if (inp[i].checkValidity() == false) {
                btn.disabled = "disabled";
            } else {
                btn.disabled = false;
            }
        }
        

      【讨论】:

        【解决方案3】:
        <form name="theform">
            <input type="text" />
            <input type="text" />`enter code here`
            <input id="submitbutton" type="submit"disabled="disabled" value="Submit"/>
        </form>
        
        <script type="text/javascript" language="javascript">
        
            let txt = document.querySelectorAll('[type="text"]');
            for (let i = 0; i < txt.length; i++) {
                txt[i].oninput = () => {
                    if (!(txt[0].value == '') && !(txt[1].value == '')) {
                        submitbutton.removeAttribute('disabled')
                    }
                }
            }
        </script>
        

        【讨论】:

          【解决方案4】:

          我认为这对于 JavaScript 初学者来说会简单得多

              //The function checks if the password and confirm password match
              // Then disables the submit button for mismatch but enables if they match
                      function checkPass()
                      {
                          //Store the password field objects into variables ...
                          var pass1 = document.getElementById("register-password");
                          var pass2 = document.getElementById("confirm-password");
                          //Store the Confimation Message Object ...
                          var message = document.getElementById('confirmMessage');
                          //Set the colors we will be using ...
                          var goodColor = "#66cc66";
                          var badColor = "#ff6666";
                          //Compare the values in the password field 
                          //and the confirmation field
                          if(pass1.value == pass2.value){
                              //The passwords match. 
                              //Set the color to the good color and inform
                              //the user that they have entered the correct password 
                              pass2.style.backgroundColor = goodColor;
                              message.style.color = goodColor;
                              message.innerHTML = "Passwords Match!"
           //Enables the submit button when there's no mismatch                   
                              var tabPom = document.getElementById("btnSignUp");
                              $(tabPom ).prop('disabled', false);
                          }else{
                              //The passwords do not match.
                              //Set the color to the bad color and
                              //notify the user.
                              pass2.style.backgroundColor = badColor;
                              message.style.color = badColor;
                              message.innerHTML = "Passwords Do Not Match!"
           //Disables the submit button when there's mismatch       
                              var tabPom = document.getElementById("btnSignUp");
                              $(tabPom ).prop('disabled', true);
                          }
                      } 
          

          【讨论】:

            【解决方案5】:

            这里是代码

            <html>
               <body>
                  <input type="text" name="name" id="name" required="required"                                    aria-required="true" pattern="[a-z]{1,5}" onchange="func()">
                  <script>
                   function func()
                   {
                    var namdata=document.form1.name.value;
                     if(namdata.match("[a-z]{1,5}"))
                    {
                     document.getElementById("but1").disabled=false;
                    }
                    }
                    </script>
              </body>
            </html>
            

            使用Javascript

            【讨论】:

            • 只使用 required 属性就足够了对吧?因为如果未填写必填字段,则提交按钮中的操作不会执行。它告诉用户填写必填字段。这是 HTML 5 中的一项新功能
            【解决方案6】:

            我刚刚在Disable Submit button until Input fields filled in 上发布了这个。对我有用。

            使用提交时的表单。干净整洁。您不必担心更改和按键事件触发。不必担心键位和焦点问题。

            http://www.w3schools.com/jsref/event_form_onsubmit.asp

            <form action="formpost.php" method="POST" onsubmit="return validateCreditCardForm()">
               ...
            </form>
            
            function validateCreditCardForm(){
                var result = false;
                if (($('#billing-cc-exp').val().length > 0) &&
                    ($('#billing-cvv').val().length  > 0) &&
                    ($('#billing-cc-number').val().length > 0)) {
                        result = true;
                }
                return result;
            }
            

            【讨论】:

              【解决方案7】:

              把它放在桌子里,然后在她身上做:

              var tabPom = document.getElementById("tabPomId");
              $(tabPom ).prop('disabled', true/false);
              

              【讨论】:

              • 为此需要 jQuery。
              【解决方案8】:

              只需添加一个else 然后:

              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;
                  }
                  else {
                      document.getElementById('submitbutton').disabled = 'disabled';
                  }
              }
              

              【讨论】:

              • 没有。并且不要(尝试)将布尔属性设置为字符串值。
              • @Bergi 我只是在扩展 OP 的代码。如果您想告诉 OP 不要在字符串属性上使用布尔值,那么我建议在问题中添加评论而不是我的答案;)
              【解决方案9】:

              随便用

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

              而不是只适用于单向的 if 子句。

              另外,对于禁用 JS 的用户,我建议仅通过 JS 设置初始 disabled。为此,只需将脚本移到&lt;form&gt; 后面并调用checkform(); 一次。

              【讨论】:

              • 我试着摆弄这个没有运气。你介意提供一个jsfiddle吗?谢谢。
              • 没有 if 语句,我说。此外,如果您将 jsfiddle 配置为执行脚本 onload,则函数和变量声明将对匿名函数是本地的,并且不能从内联处理程序中访问。使用不换行选项。 jsfiddle.net/6yPvg/3
              • Bergi,非常感谢,特别是关于onload的解释。
              • 一个问题:它与字段集中断。
              • 是的,您的 document.forms["theform"].elements 包含没有 value 属性的 &lt;fieldset&gt; 元素。您需要更好地指定您的元素列表,或测试 f[i] 是否是文本输入 (simple fix)。
              猜你喜欢
              • 1970-01-01
              • 2014-07-25
              • 2013-01-14
              • 1970-01-01
              • 2013-05-21
              • 2023-03-23
              • 2017-12-30
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多