如何根据复选框状态禁用/启用提交按钮?

Posted

技术标签:

【中文标题】如何根据复选框状态禁用/启用提交按钮?【英文标题】:How to disable/enable submit button depending on checkbox state? 【发布时间】:2019-06-02 16:04:37 【问题描述】:

有一个包含两个文本字段和一个复选框的表单,它们都是必需的并且具有 required 属性。

只有在填写并检查了所需的输入后,才能启用提交按钮。

使用当前代码,文本字段验证似乎可以正常工作,但对复选框没有影响。

Jsfiddle

<form action="#otherForm">
   Name * <input name="otherForm-name1" placeholder="required" required> <br />
   Tel * <input name="otherForm-surname" placeholder="required" required> <br />
   <input type="checkbox" name="otherForm-chcekbox" required><label for="otherForm-chcekbox">I agree</label> <br />
   <button id="otherForm-submitBtn" class="monitored-btn" type="submit">Submit</button>
</form>

<script>
    const inputSelector = ':input[required]:visible';

    function checkForm() 
        // here, "this" is an input element
        var isValidForm = true;
        $(this.form).find(inputSelector).each(function() 
            if (!this.value.trim()) 
                isValidForm = false;
            
        );
        $(this.form).find('.monitored-btn').prop('disabled', !isValidForm);
        return isValidForm;
    
    $('.monitored-btn').closest('form')
        // in a user hacked to remove "disabled" attribute, also monitor the submit event
        .submit(function() 
            // launch checkForm for the first encountered input,
            // use its return value to prevent default if form is not valid
            return checkForm.apply($(this).find(':input')[0]);
        )
        .find(inputSelector).keyup(checkForm).keyup();
</script>

【问题讨论】:

此表单中不需要复选框。只需将其替换为 By submitting this form I agree with &lt;whatever I should agree&gt; 之类的文本即可。 @KoshVery——在许多司法管辖区,根据具体情况,复选框是必需的。 @RobG,您能否提供一些相应法律的链接? @KoshVery 这不是某种法律咨询论坛,但在许多情况下,您需要用户的明确同意而不是默示同意。 GDPR 就是一个例子,用户需要明确同意才能收集他们的数据。 @KoshVery—我为客户工作过的法律建议说,如果要求消费者同意条款和条件,则需要一个复选框(或类似的 UI 小部件),所以我将它们放入.它们不能被预先选中,用户必须实际选中复选框并选中它。如果您在消费者电子商务网站上工作,您很快就会发现,如果司法管辖区要求(并且 BA 已正确完成他们的工作),这可能是一项明确的要求。如果您想要更多,请寻求自己的建议。 【参考方案1】:

我会这样做与 Kubwimana Adrien 的回答非常相似,最初呈现一个禁用的按钮。

此外,通常将验证布尔值的初始状态设置为 TRUE 是不安全的。因此,稍微修改一下代码。

    const inputSelector = ':input[required]:visible';

    function checkForm() 
        // here, "this" is an input element
        var isValidForm = false;
        $(this.form).find(inputSelector).each(function() 
            if (((this.type != 'checkbox') && (this.value.trim() != "")) || (this.type == 'checkbox' && this.checked)) 
                isValidForm = true;
            
            else
            	isValidForm = false
                return false //break out of each loop
            
        );
        $(this.form).find('.monitored-btn').prop('disabled', !isValidForm);
        return isValidForm;
    
    $('.monitored-btn').closest('form')
        // in a user hacked to remove "disabled" attribute, also monitor the submit event
        .submit(function() 
            // launch checkForm for the first encountered input,
            // use its return value to prevent default if form is not valid
            return checkForm.apply($(this).find(':input')[0]);
        )
        .find(inputSelector).on("keyup change", checkForm);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
  <form action="#otherForm">
         Name * <input name="otherForm-name1" placeholder="required" required> <br />
         Tel * <input name="otherForm-surname" placeholder="required" required> <br />
         <input type="checkbox" name="otherForm-chcekbox" required><label for="otherForm-chcekbox">I agree</label> <br />
         <button id="otherForm-submitBtn" class="monitored-btn" type="submit" disabled>Submit</button>
  </form></body>

【讨论】:

【参考方案2】:

仅需要 CSS

#otherForm-submitBtn 
  enabled: false;
  color: grey;


input[type='checkbox']:checked ~ #otherForm-submitBtn 
  enabled: true;
  color: black;
<form action="#otherForm">
   Name * <input name="otherForm-name1" placeholder="required" required> <br />
   Tel * <input name="otherForm-surname" placeholder="required" required> <br />
   <input type="checkbox" name="otherForm-chcekbox" required><label for="otherForm-chcekbox">I agree</label> <br />
   <button id="otherForm-submitBtn" class="monitored-btn" type="submit">Submit</button>
</form>

【讨论】:

给定“只有在填写并检查了所需的输入后才能启用提交按钮。”,这需要检查其他控件是否也有效。 不错的尝试,但“禁用”按钮仍然可以点击(至少在 FF 中)。尝试使用pointer-events 属性。 感谢@KoshVery,我认为 RobG 指出,在现实世界中,随着时间的推移,复杂的形式可能会发生变化,动态扫描类标签控件的脚本函数将是一个更好的解决方案。【参考方案3】:

Keyup 事件在复选框上不起作用,最好检查选中的道具而不是复选框上的值。试试这个:

const inputSelector = ':input[required]:visible';
function checkForm() 
  // here, "this" is an input element
  var isValidForm = true; 
  $(this.form).find(inputSelector).each(function() 
    if (!this.value.trim() || (this.type == 'checkbox' && !this.checked)) 
      isValidForm = false;
    
  );
  $(this.form).find('.monitored-btn').prop('disabled', !isValidForm);
  return isValidForm;

$('.monitored-btn').closest('form')
  // in a user hacked to remove "disabled" attribute, also monitor the submit event
  .submit(function() 
    // launch checkForm for the first encountered input,
    // use its return value to prevent default if form is not valid
    return checkForm.apply($(this).find(':input')[0]);
  )
  .find(inputSelector).on("keyup change", checkForm);

【讨论】:

【参考方案4】:

您需要在每次用户键入或单击复选框时检查该条件,并通过 removeAttrattr 切换禁用 ..

$("form input").keyup(check);
$("form input:checkbox").on("click", check);

function check()   
 if($("input[name='otherForm-name1']").val() != "" &&
   $("input[name='otherForm-surname']").val() != "" &&
   $("input[name='otherForm-chcekbox']").prop("checked") == true) 
     $("#otherForm-submitBtn").removeAttr("disabled");
     return;
   
   $("#otherForm-submitBtn").attr("disabled",true);
   
  
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="#otherForm">
   Name * <input name="otherForm-name1" placeholder="required" required> <br />
   Tel * <input name="otherForm-surname" placeholder="required" required> <br />
   <input type="checkbox" name="otherForm-chcekbox" id="otherForm-chcekbox" required><label for="otherForm-chcekbox">I agree</label> <br />
   <button id="otherForm-submitBtn" class="monitored-btn" type="submit" disabled>Submit</button>
</form>

【讨论】:

【参考方案5】:

禁用具有禁用属性的按钮。然后监听复选框更改事件,然后删除或添加属性。

<form action="#otherForm">
    <input type="checkbox" name="otherForm-chcekbox" required><label for="otherForm-chcekbox">I agree</label> <br />
   <button id="otherForm-submitBtn" class="monitored-btn" type="submit" disabled>Submit</button>
</form>



$(".otherForm-chcekbox").change(function() 
    if(this.checked) 
      if (checkForm()) 
        $("otherForm-submitBtn").removeAttr("disabled");   
      
     else 
      $("otherForm-submitBtn").attr("disabled", "disabled");   
    
);

【讨论】:

给定“只有在填写并检查了所需的输入后才能启用提交按钮。”,这需要检查其他控件是否也有效。 @RobG 是的,错过了。在删除属性之前,我已经更新了调用 checkForm 函数的答案。 另外,不要将.attr() 用于布尔属性/道具。请改用.prop() @Terry。好的,当然。但是它们可以互换,对吗?使用 attr 是否存在性能缺陷?还是只是对非字符串属性使用 prop() 的原则? 当您删除某个属性时,您无法在某些浏览器中重新添加它:请参阅***.com/questions/5874652/prop-vs-attr

以上是关于如何根据复选框状态禁用/启用提交按钮?的主要内容,如果未能解决你的问题,请参考以下文章

根据禁用/启用状态替换按钮文本

jquery验证检查3个复选框的状态都被选中然后启用按钮

禁用或启用复选框已选中事件的提交按钮

jquery根据状态数组禁用提交按钮

如何根据带有闪亮元素的 R Markdown 文档中的条件禁用按钮?

选中复选框后启用提交按钮