473,396 Members | 1,864 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

Listener that stops execution

Frinavale
9,735 Expert Mod 8TB
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
14 2648
Dormilich
8,658 Expert Mod 8TB
@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
9,735 Expert Mod 8TB
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
9,735 Expert Mod 8TB
I'm so incredibly stuck :(
I have run out of ideas on what to research next....
Mar 2 '09 #4
gits
5,390 Expert Mod 4TB
... 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
9,735 Expert Mod 8TB
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
9,735 Expert Mod 8TB
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
9,735 Expert Mod 8TB
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
9,735 Expert Mod 8TB
Thank you guys so much for your help!
Things are coming together very quickly now.
Mar 3 '09 #9
gits
5,390 Expert Mod 4TB
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
9,735 Expert Mod 8TB
@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
5,390 Expert Mod 4TB
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
9,735 Expert Mod 8TB
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
9,735 Expert Mod 8TB
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
9,735 Expert Mod 8TB
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

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

Similar topics

2
by: Cherrish Vaidiyan | last post by:
Hello all, A warm Xmas greetings to all. I have a small problem with starting up the database. Here my strategy. I have installed Oracle 9i R 2 on Red Hat 9. i created two database on this...
1
by: Cherrish Vaidiyan | last post by:
sir, I have a small error in Listener configuration.I have two system with a database in each. I am using Red Hat 9 and Oracle 9i. so i shall anme the database and system. system 1 - node2 ...
5
by: Axel Dachtler | last post by:
Hi, I have a listener problem. The listener cannot read SERVICE_NAME in TNS-Descriptor. The service-name I specified in Oracle Net Manager for this database is testdb as well. ...
3
by: Bill | last post by:
When vb6 Winsock.RemoteHost is set to "127.0.0.1", c# socket listener cannot hear connect request (my old vb6 winsock listener could hear it...). Why doesn't this work, and is there a work...
5
by: Adrian Enders | last post by:
I have something that I have never seen before in a MS development product. I have a pretty simple call to a network directory that looks something like this ... Dim dirFolder As...
6
by: Steve Teeples | last post by:
I have been perplexed by how to best treat an event that spans different classes. For example, I have a form which a user inputs data. I want to broadcast that data via an event to another...
5
by: mivey4 | last post by:
Hi, First off, I am aware that this is a very heavily documented error and I have done my homework for throughly researching probable causes before deciding to post my problem here. At this point,...
1
by: michael ngong | last post by:
michael.john@gmx.at (Michael John) wrote in message news:<90cc4edd.0306230900.28075193@posting.google.com>... MIchael I you stated the OS and platform that could make it easier to address your...
9
by: Markgoldin | last post by:
Here is my code to create a TCP listener: file name DataAdapterLauncher.cs public static TcpListener tcpl; IPEndPoint ipe = new IPEndPoint(IPAddress.Parse("0.0.0.0"), 1024);//listen on all local...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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,...
0
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...
0
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...
0
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,...

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.