How JQuery data validation plugin works on the submit action
I am learning how to use JQuery validation plugin,
and came across some questions about the JQuery magic that works on the sumbit action. I got a simple HTML form which has got an input text field like this:<form class="cmxform" id="commentForm" method="get" action="">
<input id="cname" name="name" size="25" class="required" minlength="2" />
<input class="submit" type="submit" value="Submit"/>
</form>
The magic happened when I tried not to input any data into the field and pressed the
submit button. I saw an error message in red pop up, and no matter how hard and how many times I pressed the submit button, nothing was subm开发者_StackOverflowitted.It seemed that there were some scripts that disabled the submit action,
but I just couldn't find which lines of codes in the JQuery Validatyion Plugin that did it. I want to learn how it works from examples.What I would do is change the submit button to a button button that way your not confusing the action. After which, you will manually submit the form once it validates. It will look something like this:
<head>
<script type="text/javascript">
//form validation setup
var setupFormValidation = function(){
//bind the click event to the new button with id submit-form
$("#submit-form").click(function(){
submitForm();
});
//setup validation on commentForm
$("#commentForm").validate({
errorLabelContainer: $("div#formerror"),
rules: {
name: { required: true }
},
messages:{
name: "please enter your name"
}
});
}
//define submitForm function
//this manually submits form
var submitForm = function(){
document.cmxForm.submit();
}
//document loaded
$(document).ready(function() {
//set up your form validation
setupFormValidation();
});
</script>
</head>
<!-- add your form error div -->
<div id="formerror"></div>
<!-- added name = cmfForm -->
<form class="cmxform" id="commentForm" method="get" action="" name="cmxForm">
<input id="cname" name="name" size="25" class="required" minlength="2" />
<!-- changed from submit to button with id of submit-form for jquery -->
<input type="button" class="submit" id="submit-form" value="Submit"/>
</form>
try following to understand this:
put this in the page
<script type="text/javascript">
$(document).ready(function() {
$("#btnSubmit").click(function(){confirm("Are you sure ?");});
});
</script>
you will see that, if you click in cancel, submit action doesn´t happen. This is why when you return false in the button, you cancel the postback, when you return true, the postback happens.
If your looking at the examples for JQuery Validate, the following code kills the submit action.
$.validator.setDefaults({
submitHandler: function() { alert("submitted!"); }
});
精彩评论