我有一个简单的表单,它有一个复选框和 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/