By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
459,654 Members | 1,513 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 459,654 IT Pros & Developers. It's quick & easy.

Listener that stops execution

Frinavale
Expert Mod 5K+
P: 9,731
Whenever I have an ASP.NET button on a page that I don't want to post back to the server if some client side check has failed I simply have the button's JavaScript "onclick" event return false:

Expand|Select|Wrap|Line Numbers
  1. <input type="button" id="myAspNetButton" value="my asp.net button" onclick="return myJavaScriptFunction();"></input>
How do I accomplish the same thing using an event listener?
Mar 2 '09 #1
Share this Question
Share on Google+
14 Replies


Dormilich
Expert Mod 5K+
P: 8,639
@Frinavale
I'd like to know that too (trying already some days on that, but no success so far)

If that route fails I can only imagine a Javascript only route that removes the submit button and does a form.submit() on validation success.

note: as per DTD, <input> is an empty element (if validation matters)
Mar 2 '09 #2

Frinavale
Expert Mod 5K+
P: 9,731
At first I thought that I might be able to do this by specifying that I'm handling the event....(got the idea from here but realized where I was going wrong after reading this article) I thought that you have to specify that you are handling the event and stop the event from being bubbled back up.

For example:
Expand|Select|Wrap|Line Numbers
  1. function doSomething(e) {
  2.     if (!e) var e = window.event
  3.     // handle event
  4.     e.cancelBubble = true;
  5.     if (e.stopPropagation) e.stopPropagation();
  6. }
  7.  

But this is not right............

I really don't know how to stop it from continuing.
Mar 2 '09 #3

Frinavale
Expert Mod 5K+
P: 9,731
I'm so incredibly stuck :(
I have run out of ideas on what to research next....
Mar 2 '09 #4

gits
Expert Mod 5K+
P: 5,390
... i hope that i get it right ... basicly it is a submit-button that submits a form and you want to cancel the submit-action when any validation fails ... and you added an eventlistener the 'cool' way instead of using the onclick? ... is that the correct description of the problem?

kind regards
Mar 3 '09 #5

Frinavale
Expert Mod 5K+
P: 9,731
Yes, but it's not only applied to submit buttons, it's also applied to selects (DropDownLists) and hyperlinks etc.
Mar 3 '09 #6

Frinavale
Expert Mod 5K+
P: 9,731
I have no idea how to do this using pure JavaScript but Microsoft has figured it out.

They have provided a method in the Ajax Library that prevents the original event from continuing....it cancels the event.

The method is called preventDefault and it is part of the Sys.UI.DomEvent Class.

When using the Ajax Library, events are converted into Sys.UI.DomEvents. This gave me the ability stop the cancel the original event when I require it to be cancelled.

Now I have a whole lot of new problems/questions to solve.....but at least I'm passed this huge obstacle.

-Frinny
Mar 3 '09 #7

Frinavale
Expert Mod 5K+
P: 9,731
Oh!

It is easy with regular JavaScript!

There's a event.preventDefault method!!

Microsoft just wanted to make it seem like it's their method by exposing the regular JavaScript event.preventDefault method through the Sys.UI.DomEvent class.
Mar 3 '09 #8

Frinavale
Expert Mod 5K+
P: 9,731
Thank you guys so much for your help!
Things are coming together very quickly now.
Mar 3 '09 #9

gits
Expert Mod 5K+
P: 5,390
hi ...

;) nice that you figured it out ;) ... and yes ... preventDefault() cancels the default-action that is assigned to a control's event (node's event) in Mozilla, to stop the further propagation you just need to call the stopPropagation() method additionally

kind regards
gits
Mar 3 '09 #10

Frinavale
Expert Mod 5K+
P: 9,731
@gits
Is there a different method to do this in IE?

@gits
Yeah that's what I thought was needed originally but apparently the combination of the two methods is required if the method handles the event and wants to prevent it from being bubbled up to the parent.
Mar 3 '09 #11

gits
Expert Mod 5K+
P: 5,390
it seems that only newer IEs supports that method? you might have a look here ... and you may consider writing a common method 'cancelEvent(e)' that handles all this ;)

kind regards
gits
Mar 3 '09 #12

Frinavale
Expert Mod 5K+
P: 9,731
This is interesting and confusing to me but....the preventDefault method does not prevent the default action of a <select> element.

I've been using the w3c "try-it" editor for all of my testing. To see what I'm trying to do you can just replace the code in the try-it editor with the following code...

What I'm finding is that the <select> element is still permitted to change even though I have called the preventDefault() method...

When I raise the "change" event (by clicking the "simulate change" button) it says the event is cancelled, but I have no way of knowing if this is true... and besides that, I'm able to change the selected index by clicking the <select> and choosing a new value.

Do you know of a way to stop this from happening?

(Note that you have to click the "Apply Handlers" to add the event listeners to the controls...otherwise the preventDefault() method will not be called)
Expand|Select|Wrap|Line Numbers
  1. <html>
  2. <head>
  3. <script type="text/javascript">
  4. var index;
  5.  
  6. function preventDef(event) {
  7.   alert("Original index: " + index.toString());
  8.   event.preventDefault();
  9. }
  10.  
  11.  
  12. function saveValue(){
  13.    index=document.getElementById("dropDownList").selectedIndex;
  14. }
  15.  
  16.  
  17. function addHandler() {
  18. alert("applying listeners");
  19. alert("applying change listener for dropDownList...");
  20.   document.getElementById("dropDownList").addEventListener("change", 
  21.     preventDef, false);
  22. alert("applying click listener for dropDownList...");
  23.  document.getElementById("dropDownList").addEventListener("click", 
  24.     saveValue, false);
  25. alert("applying click listener for mycheckbox...");
  26.  document.getElementById("mycheckbox").addEventListener("click", 
  27.     preventDef, false);
  28. alert("done");
  29. }
  30.  
  31.  
  32. function simulateSelectedIndexChanged() {
  33.   var evt = document.createEvent("HTMLEvents");
  34.   evt.initEvent("change", true, true);
  35.   var cb = document.getElementById("dropDownList"); 
  36.   var cancelled = !cb.dispatchEvent(evt);
  37.   if(cancelled) {
  38.     // A handler called preventDefault
  39.     alert("cancelled");
  40.   } else {
  41.     // None of the handlers called preventDefault
  42.     alert("not cancelled");
  43.   }
  44. }
  45.  
  46.  
  47. function simulateClick() {
  48.   var evt = document.createEvent("MouseEvents");
  49.   evt.initMouseEvent("click", true, true, window,
  50.     0, 0, 0, 0, 0, false, false, false, false, 0, null);
  51.   var cb = document.getElementById("mycheckbox"); 
  52.   var cancelled = !cb.dispatchEvent(evt);
  53.   if(cancelled) {
  54.     // A handler called preventDefault
  55.     alert("cancelled");
  56.   } else {
  57.     // None of the handlers called preventDefault
  58.     alert("not cancelled");
  59.   }
  60. }
  61. </script>
  62.  
  63. </head>
  64. <body>
  65. <div style="width:65%; margin-left:auto; margin-right:auto;">
  66.  
  67.   <div style="float:left;text-align:center">
  68.     CheckBox Case
  69.     <div style="border:solid 1px black; padding:5px; margin:5px;">
  70.       <input id="mycheckbox" type="checkbox"/>
  71.       <label for="mycheckbox">MyCheckBox</label>
  72.       <br />
  73.       <input type="button" value="Simulate click" onclick="simulateClick();" /> 
  74.     </div>
  75.   </div>
  76.  
  77.   <div style="float:right;text-align:center">
  78.     Select Case
  79.     <div  style="border:solid 1px black; padding:5px; margin:5px;">
  80.       <select id="dropDownList">
  81.         <option value="1">1</option>
  82.         <option value="2">2</option>
  83.         <option value="3">3</option
  84.       </select>
  85.       <label for="dropDownList">DropDownList</label>
  86.      <br />
  87.     <input type="button" value="Simulate change" onclick="simulateSelectedIndexChanged()"; />
  88.    </div>
  89.   </div>
  90.  
  91.   <input type="button" value="Apply Handlers" onclick="addHandler();" style="clear:both; width:100%;" />
  92. </div>
  93.  
  94. </body>
  95. </html>
Mar 6 '09 #13

Frinavale
Expert Mod 5K+
P: 9,731
Ok I noticed something else that's interesting.

The value of the checkBox actually does change! It is changed back after the preventDefault method was called.

I noticed this when I uncommented the alert and checked the checkbox (after the "onclick" listener had been applied to it):
The preventDef() method is executed during the onclick event of the checkbox and the alert was displayed. The checkbox is "checked" at the time the alert was displayed, but after the preventDefault method was called it was changed back to its original state.

So, in order to maintain the original state of the <select> item, I set it's selected index back to the original selected index (which I stored during the <select>'s onclick event).

This is not going to help me solve my problem though....in the real application my select element has code that executes a post back to the server during the onchange event:

Expand|Select|Wrap|Line Numbers
  1. <select id="myDropDownList" onchange="javascript:setTimeout('__doPostBack(\'myDropDownList\',\'\')', 0)" name="myDropDownList">
This is added by ASP.NET because the select element has been configured to let the server know when the index has changed.

If I cannot stop this onchange code from being executed, my code (that gives the user an option cancel the event from happening) will be useless.


The following code resets the <select> element back to it's original state during the onchange event, but the sayHi() method is still called...indicating that the event was not stopped....so I'm back to my original question: how do I stop the event from continuing with it's execution?
Expand|Select|Wrap|Line Numbers
  1. <html>
  2. <head>
  3. <script type="text/javascript">
  4.   var index;
  5.  
  6.   function preventDef(event) {
  7.     //alert("Original index: " + index.toString());
  8.     document.getElementById("dropDownList").selectedIndex = index;
  9.     event.preventDefault();
  10.     event.stopPropagation();
  11.   }
  12.  
  13.   function saveValue(){
  14.     index=document.getElementById("dropDownList").selectedIndex;
  15.   }
  16.  
  17.   function addListeners() {
  18.     alert("applying listeners");
  19.     alert("applying change listener for dropDownList...");
  20.     document.getElementById("dropDownList").addEventListener("change", 
  21.     preventDef, false);
  22.     alert("applying click listener for dropDownList...");
  23.     document.getElementById("dropDownList").addEventListener("click", 
  24.     saveValue, false);
  25.     alert("done");
  26.   }
  27.  
  28.   function sayHi(){
  29.     alert('hi!');
  30.   }
  31.  
  32. </script>
  33. </head>
  34.  
  35. <body onload="addListeners();">
  36.   <div style="width:50%; margin-left:auto; margin-right:auto; text-align:center;">
  37.     Select Case
  38.     <div  style="border:solid 1px black; padding:10px; margin:5px;">
  39.       <select id="dropDownList" onchange="sayHi();">
  40.         <option value="1">1</option>
  41.         <option value="2">2</option>
  42.         <option value="3">3</option
  43.       </select>
  44.       <label for="dropDownList">DropDownList</label>
  45.       <br />
  46.    </div>
  47.   </div>
  48. </body>
  49. </html>
Mar 6 '09 #14

Frinavale
Expert Mod 5K+
P: 9,731
Hmm, the event "might" actually be "cancelled".

I don't know how to tell this for sure because the selected index is changed after the preventDefault() method has been executed and I have to manually change it back if I want it to remain unchanged.

But the reason why I think it might be cancelled is because in the first code, when i simulated the "change" event, it returned that it did not execute when I attempted to raise the event.

And I've discovered that the "onchange" specified within the select element itself is executed before the listener "onchange" code is executed....which means that my assumption earlier might be incorrect...I just have no idea how to tell if it's true or false.

Even if this is true, I still need a way to prevent the onchange specified within the select element from executing if the event listener cancels the event.....

I'm confused.

Expand|Select|Wrap|Line Numbers
  1. <html>
  2. <head>
  3. <script type="text/javascript">
  4.   var index;
  5.  
  6.   function preventDef(event) {
  7.     alert("preventDef() says hi!");
  8.     document.getElementById("dropDownList").selectedIndex = index;
  9.     event.preventDefault();
  10.     event.stopPropagation();
  11.   }
  12.  
  13.   function saveValue(){
  14.     index=document.getElementById("dropDownList").selectedIndex;
  15.   }
  16.  
  17.   function addListeners() {
  18.     alert("applying listeners");
  19.     alert("applying change listener for dropDownList...");
  20.     document.getElementById("dropDownList").addEventListener("change", 
  21.     preventDef, false);
  22.     alert("applying click listener for dropDownList...");
  23.     document.getElementById("dropDownList").addEventListener("click", 
  24.     saveValue, false);
  25.     alert("done");
  26.   }
  27.  
  28.   function sayHi(){
  29.     alert('sayHi() says hi!');
  30.   }
  31.  
  32. </script>
  33. </head>
  34.  
  35. <body onload="addListeners();">
  36.   <div style="width:50%; margin-left:auto; margin-right:auto; text-align:center;">
  37.     Select Case
  38.     <div  style="border:solid 1px black; padding:10px; margin:5px;">
  39.       <select id="dropDownList" onchange="sayHi();">
  40.         <option value="1">1</option>
  41.         <option value="2">2</option>
  42.         <option value="3">3</option
  43.       </select>
  44.       <label for="dropDownList">DropDownList</label>
  45.       <br />
  46.    </div>
  47.   </div>
  48. </body>
  49. </html>
Mar 6 '09 #15

Post your reply

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