I want to perform an onclick and onsubmit at the same time, is this possible? Or if this is bad practice how can I merge the two codes to perform both events?
I have this piece of code checking a mandatory field on the form tag:
onsubmit="return formCheck(this);"
I then have this piece of code on the submit button for the same form:
onClick="jQuery.facebox({ ajax: (\'wishlist.php?emailme=true&name=\' + this.form.name.value + \'&country=\' + this.form.country.value + \'&email=\' + this.form.email.value + \'&department=\' + this.form.department.value) }); return false;"
The problem I have is that on clicking the submit button it completely ignores the onsubmit code. How can I merge them together?
UPDATE I want it to check the mandatory fields first then send the form if all is ok.
UPDATE: I’ve pasted the whole code here, I’m really struggling as this was done by a previous developer. If someone could literally put the solutions into the code that would be great. I’ll up the reward.
Put your onClick code in the same function as the onSumbit code.
UPDATE
At the end of your
onClickcode youreturn false;, this stops the normal propagation of events and stops theonSubmitevent from firing. So if you want the submit button to submit the form, removereturn false;from it’sonClickhandler.When you click a submit button you will fire a
clickevent on the button and asubmitevent on the form in which the button is nested (unless you stop the propagation of events with something likereturn false;).So you really only need a
submitevent handler that does the job of both of your current handlers.Also since it appears that you have jQuery Core included in your page you can attach event handlers like this:
If you are sending the whole form to the
jQuery.faceboxfunction then you can use jQuery’s.serialize()function to create the necessary query-string:Here is a demo: http://jsfiddle.net/vAFfj/
Docs for
.serialize(): http://api.jquery.com/serializeNote that
.on()is new in jQuery 1.7 and in this case is the same as.bind()of older versions.UPDATE
If you want to check the return value from the
formCheck()function before running thefaceboxplugin then you can do this: