I have a comments form with 2 fields in it: Author and Message. When I click the submit button the validation does not fire. If i click the submit button once more, then the validation works. Any idea why?
//User Clicked Submit Button
$('#CommentsForm').live('submit', function (e) {
e.preventDefault(); //Prevent Browser from getting new url
//Validate the comments form
$('#CommentsForm').validate({
rules: {
Author: "required",
Message: "required"
},
messages: {
Author: "Author is required.",
Message: "Comment is required."
},
errorContainer: "#CommentsErrorBox",
errorLabelContainer: "#CommentsErrorBox ul",
wrapper: "li",
submitHandler: function() {
//Create JSON object
var jsonCommentData = {
ProductID: $('#HiddenProductID').val(),
Author: $('#Author').val(),
Message: $('#Message').val()
};
//Add the comment.
$.ajax({
url: '/Home/_CommentsAdd',
type: 'POST',
data: JSON.stringify(jsonCommentData),
dataType: 'html',
contentType: 'application/json',
//The request was a success. Repopulate the div with new result set.
success: function (data) {
$('#AjaxComments').html(data);
$('abbr.timeago').timeago(); //update the timestamp with timeago
//Change colors of message.
if ($('#CommentStatus').html() == "Your Comment Has Been Added!") {
$('#CommentStatus').css('color', 'GREEN');
}
},
error: function (data) {
alert('Fail');
}
});
}
});
});
Because your first click on #CommentsForm
sets up jQuery validate:
$('#CommentsForm').validate({ ... });
Thus, any subsequent clicks are validated.
Fix:
//setup validation
var form = $('#CommentsForm');
form.validate({ /* ... setup code .... */ });
form.live('submit', function (e) {
e.preventDefault(); //Prevent Browser from getting new url
$(this).validate();
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.