javascript - 具有多个提交按钮的条件表单验证

标签 javascript jquery html forms validation

我有一个简单的表单,它有一个复选框和 3 个提交按钮。仅当单击三个按钮之一时才需要勾选复选框字段。这是表单的 html:

<form role="form" action="udpate.php" id="review" method="post">

<div class="checkbox">
<label class="checkbox">
<input type="checkbox" name="approved" value="approved">
</label>
</div>

<p>I have approved all changes and are happy to proceed</p>

<button type="submit" class="btn btn-default" name="buttonType" id="Reject"  value="Reject">Reject</button>
<button type="submit" class="btn btn-default" name="buttonType" id="Pending"  value="Pending">Pending</button>
<button type="submit" class="btn btn-default" name="buttonType" id="Approve"  value="Approve">Approve</button>
</form>

这是一个使用 jQuery 验证插件的脚本:

 <script>
     $().ready(function() {
         $("#Approve").click(function() {
             $("#review").validate(); 

        });
    });
 </script>

目前单击 3 个按钮中的任何一个都会执行验证,但我需要它仅在用户单击“批准”按钮时进行验证。只有这样才需要勾选复选框,否则如果可以留空。

是否可以进行某种验证来检查单击了哪个按钮,然后如果在继续之前单击了该按钮,还检查复选框是否为空?

最佳答案

给form和checkbox添加一个ID,例如:"form1", "checkbox1"

<form id="form1" ...>
    <input type="checkbox" id="checkbox1" ... />
    ...
</form>

然后将 jQuery 添加到当前代码中:

$('#form1 button[type="submit"]').click(function(e){
    e.preventDefault();                             // this for prevent form from submit

    if($(this).val() == "Approve"){                 // check if third button was clicked
        if($('#form1 #checkbox1').is(':checked')){  // check if checkbox is checked
            $('#form1').submit();                   // submit form
        }else{
            // here paste your info code, that checkbox is not checked
        }
    }else{                                          // any other button
        $('#form1').submit();
    }
});

关于javascript - 具有多个提交按钮的条件表单验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26404836/

相关文章:

javascript - Sequelize - 嵌套在相互覆盖的地方

Javascript:从动态生成的 ID 中获取动态 Accordion 内容

JQuery - 复选框不检查(视觉上)

jquery - 如何使用 jQuery 使一个元素在悬停另一个元素时具有 'hover' 效果(CSS)?

javascript - 停止函数事件第二次触发

html - 使用 :not to remove formatting

php - 从段落标签中剥离样式属性

javascript - html 页面中显示错误#2032

javascript - 在 Express 中设置默认响应 header

javascript - 无法使用 node.js 根据 MongoDB 中的特定字符串对值进行分组?