I'm doing some form validation, and I'm having trouble with what I'm trying to accomplish. I want to be able to validate my zip code on blur of the field, but also call the same function to validate zip on submit of the form, and prevent the form from being submitted if the zip code is invalid. My code (generically) goes something like this.
function validateZipCode(event){
$.getJson(
url,
params,
function(data){
if(data.response === false){
someError.show();
event.preventDefault(); //stop the form from being submitted
}
}
);
}
$('#someForm').submit(function(event){
validateZipCode(event);
});
$('#zipInput').blur(function(event){
validateZipCode(event);
})
I've tried using the methods located in this jQuery pass more parameters into callback post, but I still can't seem to accomplish what I need. Any help is appreciated.
preventDefault() method stops the default action of an element from happening. For example: Prevent a submit button from submitting a form. Prevent a link from following the URL.
The preventDefault() method cancels the event if it is cancelable, meaning that the default action that belongs to the event will not occur. For example, this can be useful when: Clicking on a "Submit" button, prevent it from submitting a form.
When the ajax succeeds and invokes myCallback , it will run synchronously. So myCallback is like other functions, you call it first it will run first or you call it last it will run last. THEY WILL NOT RUN AT THE SAME TIME.
Event.preventDefault() The preventDefault() method of the Event interface tells the user agent that if the event does not get explicitly handled, its default action should not be taken as it normally would be.
No, by the time the callback from the AJAX event fires, the event will have already bubbled and the form submitted. One way you could accomplish this is cancel the form from submitting and then submit it manually if it passes the requirements from the AJAX request.
You need to prevent the event's default action before it's bubbled up and handled by the browser. $.getJson returns control and allows the validateZipCode function to finish first, so you need to do this:
function validateZipCode(event){
event.preventDefault(); //stop the form from being submitted
$.getJson(
url,
params,
function(data){
if(data.response === false){
someError.show();
}
}
);
}
$('#someForm').submit(function(event){
validateZipCode(event);
});
$('#zipInput').blur(function(event){
validateZipCode(event);
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With