我有一个html表单,我首先希望使用jQuery验证库jquery.validate.min.js和 if form is valid 进行验证,将表单提交到某个位置 .
我尝试过以下方法:
<html>
<head>
<link rel="stylesheet" href="../../common/view/css/bootstrap.min.css" type="text/css">
<script src="../../common/view/js/jquery.js"></script>
<script src="../../common/view/js/bootstrap.min.js"></script>
<script src="../../common/view/js/jquery.validate.min.js"></script>
</head>
<body>
<form method="post" action="stock-c.php" id="issueform" name="issueform">
<input type="text" name="pid"/>
<input type="button" name="button1" id="button1"/>
<script type="text/javascript" src="js/issueValidation.js"></script>
<!--Modal-->
<div id="myModal" class="modal fade" role="dialog">
<div class="modal-dialog">
<!--info to be displayed-->
<input type="submit" value="submit"/> <!--Explain1-->
</div>
</div>
</from>
</body>
</html>
issueValidation.js
$( document ).ready( function () {
$validator= $( "#issueform" ).validate( {
rules: {
pid: "required",
},
messages: {
pid: "Please enter a value",
},
errorElement: "em",
errorPlacement: function ( error, element ) {
// Add the `help-block` class to the error element
error.addClass( "help-block" );
if ( element.prop( "type" ) === "checkbox" ) {
error.insertAfter( element.parent( "label" ) );
} else {
error.insertAfter( element );
}
},
highlight: function ( element, errorClass, validClass ) {
$( element ).parents( ".col-sm-5" ).addClass( "has-error" ).removeClass( "has-success" );
},
unhighlight: function (element, errorClass, validClass) {
$( element ).parents( ".col-sm-5" ).addClass( "has-success" ).removeClass( "has-error" );
}
});
$('#button1').on('click', function() {
$("#issueform").valid(); //everything works upto here
if($validator.noOfInvalids()===0){ //this code doesn't work
$('#myModal').modal('toggle');
}
});
});
Explain1: 我将提交按钮放在表单标签中的模态类中,以便在单击时提交表单数据 .
理想情况下,我想暂停提交,直到表单被验证 . 如果表单有效,我必须能够在模态中查看我的表单数据并单击其上的提交按钮,从而进行提交 .
我尝试在jQuery验证插件中使用submitHandler(仅在表单中没有invalids时才执行)来初始化模式,但为此我需要将输入[type =“button”]更改为输入[type =“submit “]因为处理程序仅适用于提交按钮 . 然后我最终得到两个相同形式的提交按钮,表单无法正确提交 .
请帮我纠正这个问题 . 作为回顾,我需要验证输入到表单的数据并在模态中请求用户确认 . 如果用户以模态确认,则表单中的数据将被提交 . 如果我的方法是实现这一结果的不必要的方法,只要它符合上述要求,也欢迎备选建议 . 谢谢 .
1 回答
这就是jQuery Validate插件已经在做的事情 .
你的代码......
As per docs,
.valid()
也返回一个布尔值,因此上面代码的点击处理程序部分可以大大简化...我知道你已经提到了这一点,但以下是为了未来读者的利益:
请注意,只有
input
是type="button"
才需要click
处理程序 .或者,当使用
type="submit"
时,不需要click
处理程序,因为插件会自动捕获点击 . 此外,在这种情况下,您将使用the submitHandler option包含表单有效时要运行的任何代码 .