I have a JavaScript Object that determines whether or not the page should be submitted to the server depending on whether the user clicks "yes" or "no".
This Object is attached to various HTML elements on the page (buttons, selects etc) and traps any events that they raise that cause the page to submit.
If the user has not responded, the Object should cancel the page submit to the server.
This is working well for Button Click events so far.
My problem happens when a JavaScript function submits the Form to the server when a Select Object's selected index changes.
My Object is implemented to prompt the user and let them cancel the event when the Select's selected index changes but the page proceeds to submit because the other JavaScript function attached to the Select submits the form. Apparently when the page is submitted to the server by this JavaScript function, the OnSubmit is completely "bypassed" and my function is never called.
When the Select causes an asynchronous call to the server (Ajax) I am able to abort/cancel the submit from happening.
When the Select causes a full page submit to the server there's not stopping it.
The following code is in the JavaScript Object's initialize implementation. It creates a "delegate" to a function that should be called when the form submits to the server. (The createDelegate method basically uses the apply method to make the Object available in the function that handles the event...see here for more information if you're interested)
Expand|Select|Wrap|Line Numbers
- this._onbeforeFormSubmitDelegate = Function.createDelegate(this, this._onbeforeFormSubmit);
- var formElement = document.getElementsByTagName("form")[0];
- $addHandler(formElement, 'submit', this._onbeforeFormSubmitDelegate);
The following code is the function that should be called when the form submits to the server.
This code is called when a button submits to the server, but is not called when the JavaScript applied to the select element submits the form to the server.
Expand|Select|Wrap|Line Numbers
- _onbeforeFormSubmit: function(e) {
- try {
- if (this.get_userConfirmed != null) {
- if (this.get_userConfirmed() == false) {
- e.stopPropagation();
- e.preventDefault();
- return false;
- }
- else {
- return true;
- }
- }
- }
- catch (ex) { }
- return true;
- }
This is the function called when the Select's selected index changes (please note that this is automatically generated by ASP.NET and I cannot change this):
Expand|Select|Wrap|Line Numbers
- var theForm = document.forms['form1'];
- if (!theForm) {
- theForm = document.form1;
- }
- function __doPostBack(eventTarget, eventArgument) {
- if (!theForm.onsubmit || (theForm.onsubmit() != false)) {
- theForm.__EVENTTARGET.value = eventTarget;
- theForm.__EVENTARGUMENT.value = eventArgument;
- theForm.submit();
- }
- }
Thanks,
-Frinny