473,729 Members | 2,340 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Cancel form submit

Frinavale
9,735 Recognized Expert Moderator Expert
I've been trying all morning to cancel a form submit to the server.

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
  1. this._onbeforeFormSubmitDelegate = Function.createDelegate(this, this._onbeforeFormSubmit);
  2.         var formElement = document.getElementsByTagName("form")[0];
  3.         $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
  1.  _onbeforeFormSubmit: function(e) {
  2.         try {
  3.             if (this.get_userConfirmed != null) {
  4.                 if (this.get_userConfirmed() == false) {
  5.                     e.stopPropagation();
  6.                     e.preventDefault();
  7.                     return false;
  8.                 }
  9.                 else {
  10.                     return true;
  11.                 }
  12.             }
  13.         }
  14.         catch (ex) { }
  15.         return true;
  16.     }

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
  1. var theForm = document.forms['form1'];
  2. if (!theForm) {
  3.   theForm = document.form1;
  4. }
  5. function __doPostBack(eventTarget, eventArgument) {
  6.    if (!theForm.onsubmit || (theForm.onsubmit() != false)) {
  7.      theForm.__EVENTTARGET.value = eventTarget;
  8.      theForm.__EVENTARGUMENT.value = eventArgument;
  9.      theForm.submit();
  10.    }
  11.  }
Any insight would be greatly appreciated.

Thanks,
-Frinny
Apr 16 '09 #1
13 10564
iam_clint
1,208 Recognized Expert Top Contributor
since your onsubmit function normally just returns a boolean value
everywhere you want to validate you run through that function first
if (onsubmitfuncti on==true) { form.submit } else { //go crazy }


javascript will not do a callback on a form submit when you use form.submit
Apr 16 '09 #2
Frinavale
9,735 Recognized Expert Moderator Expert
Sorry but I don't understand.

When my Object is loaded in the browser the "initialize " function is called.

At that point it calls a function that loops through an array of element ids which require confirmation before submitting and it dynamically applies event handlers for any events that would cause the these elements to submit the form.

This method that handles the events displays a DOM element with a message and 2 (or more) buttons allowing the user to confirm or deny the action.

Once the user has confirmed or denied the action, the Object will either close the DOM prompting the user and do nothing else or it will reissue the original event that was executed to submit the form the server as it normally would have.

In the method that dynamically applies event handlers to every control associated with the Object I am essentially "run through" the "validation " function first....

[edit]Hmm I guess I never stated this before.... but I was unable to stop the select element from submitting at this point and that is why I ended up resorting to trying to stop the form from submitting by implementing a function that handles the onsubmit event[/edit]
Apr 16 '09 #3
Frinavale
9,735 Recognized Expert Moderator Expert
Ok you are making a bit of sense actually.

I guess I should have been trying to solve the original problem instead of working around it only to run into the same problem again.

The original problem had to do stopping the select's selected index changed event in order to prevent the JavaScript associated with the select from being executed.

The following is the function that loops through all of the IDs for the elements associated with the Object and dynamically adds an event handler to the events for these elements that may cause the page to submit using the $addHandler method:

Expand|Select|Wrap|Line Numbers
  1.  set_AssociatedControlIDs: function(listOfControlIDs) {
  2.         this._listOfControlIDs = listOfControlIDs;
  3.         var len = this._listOfControlIDs.length;
  4.         for (var i = 0; i < len; i++) {
  5.             this._displayDelegate = Function.createDelegate(this, this._displayControl);
  6.             this._saveOriginalDropDownListValueDelegate = Function.createDelegate(this, this.save_originalDropDownListSettings);
  7.  
  8.             var associatedControl = $get(this._listOfControlIDs[i]);
  9.             if (associatedControl.type == 'select' || associatedControl.type == 'select-one') {
  10.  
  11.                 $addHandler(associatedControl, 'change', this._displayDelegate);
  12.                 $addHandler(associatedControl, 'click', this._saveOriginalDropDownListValueDelegate);
  13.             }
  14.             else
  15.             { $addHandler(associatedControl, 'click', this._displayDelegate); }
  16.         }
  17.     },
As you can see I'm indicating that the _displayControl () method should be called when a select's onchange event occurs. The _displayControl () method displays the DOM that prompts the user and cancels the event (if the user has not already responded).

The function that displays the DOM that prompts the user is as follows:
Expand|Select|Wrap|Line Numbers
  1.     _displayControl: function(e) {
  2.         var confirmLinkedToControl = this;
  3.         if (confirmLinkedToControl) {
  4.             if (!confirmLinkedToControl.get_userConfirmed()) {
  5.                 confirmLinkedToControl.set_currentAssociatedControlEvent(e);
  6.                 confirmLinkedToControl._showPromptWindow();
  7.                 e.preventDefault();
  8.                 e.stopPropagation();
  9.                 return false;
  10.             }
  11.             else {
  12.                 //raise the event again is done in _closeWindow() method.     
  13.                 confirmLinkedToControl._closeWindow();
  14.             }
  15.         }
  16.     },
This method does not prevent the select's JavaScript from being executed....and I think I know why. My method returning false isn't doing anything because it was applied to the element dynamically using the addHandler method.


I need to set the select's onchange event as such:
Expand|Select|Wrap|Line Numbers
  1. <select id="showConfirm" onchange="if(displayControl()==false){return false;} javascript:setTimeout('__doPostBack(\'showConfirm\',\'\')', 0)" name="showConfirm">
But I can't think of a way to do this dynamically using the addHandler method...

Any suggestions?
Apr 16 '09 #4
iam_clint
1,208 Recognized Expert Top Contributor
i'm not really reading your code in too much detail but I mean its a simple process.

Expand|Select|Wrap|Line Numbers
  1. Onchange = dostuff
  2.  
  3. dostuff {
  4.  if conditions {
  5.    __dopostback(); //assuming this is running with asp.net or something
  6.  }
  7. }
  8.  
  9. conditions {
  10. return true;
  11. }
  12.  
You are using some stuff i'm unfamiliar with but the general basics of what you are trying to do is quite simple
Apr 16 '09 #5
Frinavale
9,735 Recognized Expert Moderator Expert
I'm doing that.
The problem is stopping it from doing 'other stuff' that is put there by ASP.NET (not me)
Apr 16 '09 #6
iam_clint
1,208 Recognized Expert Top Contributor
you can set autopostback to false on elements in asp.net not sure if this is what you are looking for?
Apr 16 '09 #7
Frinavale
9,735 Recognized Expert Moderator Expert
So you're saying handle it in my .NET code.....

Set the AutoPostback = False if it's true for the DropDownList (the select element), and then manually call the __dopostback method in my JavaScript Object for any DropDownLists.

In theory this should work, but it seems a bit ugly.

Thanks acoder.
Apr 16 '09 #8
Frinavale
9,735 Recognized Expert Moderator Expert
Thank you so much acoder.

I have a working solution now :)
And I can clean up the stuff that deals with aborting Ajax requests.

I should have asked about this months ago when this problem first showed up...instead of torturing myself.


Thanks again!

-Frinny
Apr 16 '09 #9
acoder
16,027 Recognized Expert Moderator MVP
Erm, thanks, but I hadn't even posted in this thread ;)
Apr 16 '09 #10

Sign in to post your reply or Sign up for a free account.

Similar topics

3
2168
by: Jon | last post by:
Hi, I have a form. I have the code, below, to check for certain compulasry fields. The Submit button has: onClick="validate(this.form)" My problem is that the warnings come up fine, but the form still gets posted. Please can someone advise how I cancel the function if data is missing? Thank. Jon
1
5476
by: Corey Olsen | last post by:
Can anyone point me to some documentation on bypassing validation controls when a user selects cancel? What I have is a user control with a form to fill out information on a subject. The user should be presented with two buttons a "Submit" and a "Cancel". When the "Cancel" button is selected all of the items on the user control should be cleared. However, I have validation controls setup for each item necessary on the form and when...
2
3590
by: Joe C. | last post by:
Is there a way to cancel the submit process from the client using vbscript?
1
3958
by: Bucky | last post by:
I haven't found any vbscript code that can stop the form submission/postback after the msgbox. The problem is that asp:button is rendered as <input type="submit"> instead of <input type="button">. So instead of doing a "document.form(0).submit" upon "Yes", I need to stop the form submission upon "No". Javascript is easy since you can do "return confirm...", but I'm looking for a vbscript solution. Here's my relevant code: <asp:button...
10
6017
by: Andrew | last post by:
Hi, I have a messagebox that pops up due to an event. I did it in javascript. ie. alert("Time's up. Assessment Ended"); I want to capture the OK and Cancel events of this alert messagebox. My code is in C#/ASP.NET. TIA. Andrew.
0
1700
by: Stuart Whiteford | last post by:
Hi, I've got a basic web form, two textboxes, a couple of radio button groups, some required field validators, and a Submit and Cancel button. When the page loads, if I click the Cancel button, the server-side event fires as normal. However, if I click the Submit button (with no information entered) the client-side validators fire, but if I then decide to press the Cancel
4
15266
by: Martin | last post by:
I have a form with two submit buttons: <Save> and <Cancel>. When the user clicks on <Save>, I want to execute a validate function. When he clicks on <Cancel>, I want the form to submit without validation (I have server side scripting that handles the two different kinds of submits). In the "validate" function I have "return false" in the script (if the validation fails) but the form submits any way. How can I get this thing to not...
3
3646
by: No_Spam | last post by:
How do I cancel submit process if certain fields are not filled in my ASP.NET form? I need to know how to do it using the Click sub for the submit button (in the .vb file) and not using javascript, if possible.
1
2403
by: ghjk | last post by:
I'm using ajax in my php site. In there I have two buttons named as submit and cancel. When I click submit button it validates data using ajax. (No need to use form for this). But the following code is not working for cancel buttonfunction Cancel(){ cancel = document.getElementById('test').value.reset(); } If I put form,(<form name"test.php">) cancel button is working but errors return from the submit button are gone. Could someone pls...
0
9427
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9284
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9202
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9148
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8151
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6022
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
1
3238
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2683
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2165
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.