[英]Conditional Form Validation with multiple submit buttons
我有一个简单的表单,有一个复选框和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>
目前,单击这三个按钮中的任何一个都可以执行验证,但是我需要它仅在用户单击“批准”按钮时进行验证。 只有这样才需要选中该复选框,否则可以保留为空白。
是否可以进行某种验证,即先检查单击了哪个按钮,然后再检查复选框是否为空(如果在继续操作之前单击了该按钮)?
向表单和复选框添加一个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();
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.