问题
I'm using the Jquery validate function for my form validation. So far I've been appending the error message to a page element, but I now want to display it in an alert popup. The alert popup successfully displays the error message when the user has not selected anything, however the pop still appears when they submit a valid form (this time without the error message).
How do I stop the popup from appearing after a valid form submission?
Here is my js code, I've implemented the alert for radio buttons. You can see this in action on http://hiplogger.hip-zone.co.za/partner/mobile
$("#quickieform").validate({
rules: {
answer: "required"
},
answer: {
answer: "Please make a selection"
},
errorPlacement: function(error, element) {
if ( element.is(":radio") )
alert(error.html());
else if ( element.is(":checkbox") )
error.appendTo( ("#alertbox") );
else
error.appendTo( ("#alertbox") );
},
submitHandler: function(form) {
// do other stuff for a valid form
form.submit();
},
success: function(label) {
// set as text for IE
label.html(" ").addClass("checked");
}
});
回答1:
Thanks for your response. I got it working but I've no idea why its working. All I did was to take out the "success:" section at the end, so my code ended up looking like this...
$("#quickieform").validate({
rules: {
answer: "required"
},
invalidHandler: function(form, validator) {
},
errorPlacement: function(error, element) {
if ( element.is(":radio") && error.html != "")
// error.appendTo( ("#alertbox") );
alert(error.html());
else if ( element.is(":checkbox") )
// error.appendTo( ("#alertbox") );
alert(error.html());
else
error.appendTo( ("#alertbox") );
},
submitHandler: function(form) {
form.submit();
}
})
回答2:
Could it be that errorPlacement runs regardless of an actual error. This may be the case because when you run $("#quickieform").valid()
it runs validation - trips the alert then returns true
. I didn't see an actual error message in the alert. You may want to move that to the invalidHandler
function:
$("#quickieform").validate({
rules: ...
answer: ...
invalidHandler: function(form, validator) {
var errors = validator.numberOfInvalids();
if (errors) {
alert("You have " + error + " errors that need to be fixed");
}
}
...
})
or just modify your errorPlacement to also check that error.html != ""
if ( element.is(":radio") && error.html != "")
Hope this helps!
来源:https://stackoverflow.com/questions/9647855/jquery-form-validation-with-alert-popup-alert-still-being-shown-with-a-valid-s