这是我第一次使用插件和.validate()方法。现在我有一个表单,每次单击提交按钮时,它都会运行而不进行表单验证。这是我的代码:
<form class="form d" method="post" action="">
<input type="text" name="searchtitle" id="searchtitle" placeholder="Enter the textbook's title">
<input type="text" name="searchauthor" id="searchauthor" placeholder="Enter the textbook's author">
<input type="text" name="searchpublisher" id="searchpublisher" placeholder="Enter the textbook's Publisher">
<input type="text" name="searchedition" id="searchedition" placeholder="Enter the textbook's edition">
<select name="searchuniversity" id="searchuniversity"></select>
<select name="searchuniversitycampus" id="searchuniversitycampus" ></select>
<input type="submit" id ="searchsubmit" name="searchsubmit" value="Search">
</form>
然后我有以下Javascript:
$(document).on('pageinit',"#searchpage",
//this funciton will carry out the things we need to do to carry out our search
function(e)
{
e.preventDefault();
$(".form.d").validate({
rules: {
name: {
required: true
},
email: {
required: true,
email: true
},
comments: {
required: true,
minlength: 5,
nourl: true
}
},
messages: {
name: "Required Field",
email: "Valid Email Required",
comments: "Required Field + No URL's"
}
});
$("#searchsubmit").click(
function(e)
{
//Do a lot of processing here
});
});
就像我说的那样,我对形成验证和使用函数非常陌生。
Here是问题的解决方法。当您点击小提琴中的提交时,它会提示“hello”,然后进行验证。如何阻止这种情况发生。即首先验证然后运行函数?
答案 0 :(得分:2)
您的整个问题是您的click
处理程序。该插件已经内置了回调函数,可以捕获提交按钮的click
事件。当表单有效时,使用submitHandler
触发函数。当表单无效时,使用invalidHandler
触发函数。
你的jsFiddle中已经有submitHandler
回调,所以我重构你的jsFiddle代码如下:
$(document).on('pageinit', function(){
$('#myform').validate({ // initialize the plugin
rules: {
field1: {
required: true
},
field2: {
required: true
}
},
submitHandler: function (form) {
alert("hello"); // stuff to do when form is valid
alert('valid form submitted'); // for demo
return false;
},
invalidHandler: function () {
// stuff to do when form is invalid
alert("invalid form"); // for demo
}
});
// remove click handler
// use the plugin's built-in callback functions instead
//$("#test").click(function(){alert("hello")});
});
DEMO:http://jsfiddle.net/BTwaP/1/
See documentation for all callback functions
修改强>:
As of jQuery Mobile version 1.4, the pageinit
event has been deprecated and replaced with pagecreate