473,809 Members | 2,791 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Prevent RadioButton Selection

Frinavale
9,735 Recognized Expert Moderator Expert
I am trying to ask the user for confirmation before a radio button is selected.

Currently I'm handling the radio button's onclick event, asking the user to confirm their action and if they hit the 'cancel' button call the preventDefault( ) method for the event to cancel it.

It cancels the event if a selection has already been made for the radio button group (it actually selects it, the reverts it back to it's original value when the preventDefault( ) method is called) The problem I'm having is that the radio button is selected regardless of stopping the event if no previous selection has been made. When a radio button is not part of a group of radio buttons this radio button is always selected.

If you take the following code and past it into the code pane in the w3c schools try-it utility (click hit the 'Edit and Click Me' button) you'll get a good idea of what I"m trying to explain (Please note the following code does not work in IE)
Expand|Select|Wrap|Line Numbers
  1. <html>
  2.   <head>
  3.     <script type="text/javascript">
  4.     function doClick(e){
  5.       if(confirm("are you sure?")==false){
  6.         e.preventDefault();
  7.         e.stopPropagation();
  8.         return false;
  9.       }
  10.       return true;
  11.     }
  12.     </script>
  13.   </head>
  14.   <body>
  15.     <form>
  16.       <input type="radio" name="radio1" onclick="doClick(event);" />x
  17.       <input type="radio" name="radio1" onclick="doClick(event);" />y
  18.       <input type="radio" name="radio1" onclick="doClick(event);" />z
  19.     </form>
  20.   </body>
  21. </html>
Apr 20 '09 #1
6 14949
Frinavale
9,735 Recognized Expert Moderator Expert
The only way I was able to get around this was to check if the radio button had a selection to begin with (when the page is loaded) ...then later check if this value is true or false. If it didn't have a selection when the page is loaded, loop through the radio buttons and deselect each one.

This is not a clean solution and I don't know how I'm going to implement it in my application without storing some sort of array of booleans....

Expand|Select|Wrap|Line Numbers
  1. <html>
  2.   <head>
  3.     <script type="text/javascript">
  4.     var radioIsSelected;
  5.     function doClick(e){
  6.       if(confirm("are you sure?")==false){
  7.         if(radioIsSelected == false){
  8.           var radio1 = document.getElementsByName('radio1');
  9.           for(var i=0; i<radio1.length; i++)
  10.           { 
  11.             radio1[i].checked = false;
  12.           }
  13.         }
  14.         e.preventDefault();
  15.         e.stopPropagation();
  16.         return false;
  17.       }else{
  18.         radioIsSelected = true;
  19.       }
  20.       return true;
  21.     }
  22.     function checkChecked(){
  23.       var radio1 = document.getElementsByName('radio1');
  24.       radioIsSelected = false;
  25.       for(var i=0; i<radio1.length && radioIsSelected==false ; i++)
  26.       { 
  27.         if(radio1[i].checked){
  28.           radioIsSelected = true;
  29.         }
  30.       }
  31.     }
  32.     </script>
  33.   </head>
  34.   <body onload="checkChecked();">
  35.     <form>
  36.       <input type="radio" name="radio1" onclick="doClick(event);" />x
  37.       <input type="radio" name="radio1" onclick="doClick(event);" />y
  38.       <input type="radio" name="radio1" onclick="doClick(event);" />z
  39.     </form>
  40.   </body>
  41. </html>

Does anyone know a way around this problem that doesn't involve checking whether or not the radio button has a selection on page load?

-Frinny
Apr 20 '09 #2
Frinavale
9,735 Recognized Expert Moderator Expert
I found a better way :)
Again, I'm not sure if this works in IE because I haven't tried it there yet but there is a defaultChecked property for radio buttons.

All I had to do was set the checked property to the defaultChecked property during the cancel action:
Expand|Select|Wrap|Line Numbers
  1. <html>
  2.   <head>
  3.     <script type="text/javascript">
  4.     function doClick(e){
  5.       if(confirm("are you sure?")==false){
  6.         e.target.checked = e.target.defaultChecked;
  7.         e.preventDefault();
  8.         e.stopPropagation();
  9.         return false;
  10.       }
  11.       return true;
  12.     }
  13.     </script>
  14.   </head>
  15.   <body>
  16.     <form>
  17.       <input type="radio" name="radio1" id="xRadio" onclick="doClick(event);" />x
  18.       <input type="radio" name="radio1" id="yRadio" onclick="doClick(event);" />y
  19.       <input type="radio" name="radio1" id="zRadio" onclick="doClick(event);" />z
  20.     </form>
  21.   </body>
  22. </html>
Apr 21 '09 #3
acoder
16,027 Recognized Expert Moderator MVP
For IE, use:
Expand|Select|Wrap|Line Numbers
  1. e.returnValue = false;
  2. e.cancelBubble = true;
Test for support of the DOM standard methods and, if not present, try these statements for IE.
Apr 21 '09 #4
Frinavale
9,735 Recognized Expert Moderator Expert
I tested what you've suggested.

It sort of works. It works when there is no default selection and cancel the action (the option is unselected); however, if there is a default selection and the user cancels the action, the previous selection is lost: the option is unselected but the previously selected option is not re-selected.

I'm going to look into this further tomorrow.

This is what I've been testing with:
Expand|Select|Wrap|Line Numbers
  1. <html>
  2.   <head>
  3.     <script type="text/JavaScript">
  4.       function doClick(e){
  5.         if(confirm("are you sure?")==false){
  6.           try{
  7.             e.target.checked = e.target.defaultChecked;
  8.             e.preventDefault();
  9.             e.stopPropagation();
  10.             return false;
  11.           }catch(ex){
  12.             e.returnValue = false;
  13.             e.cancelBubble = true;
  14.             return true;
  15.           }
  16.         }
  17.         return true;
  18.       }
  19.     </script> 
  20.   </head>
  21.   <body>
  22.     <input type="radio" name="radio1" id="xRadio" onclick="doClick(event);" />x
  23.     <input type="radio" name="radio1" id="yRadio" onclick="doClick(event);" />y
  24.     <input type="radio" name="radio1" id="zRadio" onclick="doClick(event);" />z
  25.   </body>
  26. </htm>
Thanks acoder :)
Apr 21 '09 #5
Frinavale
9,735 Recognized Expert Moderator Expert
Well I finally got back to looking into this problem.

When using the defaultChecked property to reset the target's checked value in FireFox, the radio button that was previously selected is re-selected.

When using the defaultChecked property to reset the target's (the sourcElement's) checked value in IE, the radio button that was previously selected is not reselected.

So, in order to determine which radio button was previously selected, this script stores the default selection in a variable named selectedDefault . It uses this stored radio button to reset the selection if the user cancels.

Expand|Select|Wrap|Line Numbers
  1. <html>
  2.   <head>
  3.  
  4.     <script type="text/javascript">
  5.     var selectedDefault; // used to remember the radio button selected 
  6.     function doClick(e){
  7.       if(confirm("are you sure?")==false){
  8.         try{
  9.           // FireFox case.
  10.           // Setting the target.checked property to the defaultChecked will
  11.          // deselect the current radio button and select the radio button that
  12.          // was previously selected.
  13.           e.target.checked = e.target.defaultChecked;
  14.           e.preventDefault();
  15.           e.stopPropagation();
  16.         }catch(ex){
  17.           // Internet Explorer case.
  18.           // Setting the target.checked property to the defaultChecked does not
  19.          // deselect the current radio button and select the radio button that
  20.          // was previously selected.
  21.  
  22.          // The following selects the radio button that was previously selected
  23.           if(selectedDefault){
  24.             selectedDefault.checked = true;
  25.           }
  26.           //Deselecting the radio button that was the event's target
  27.           e.srcElement.checked = false;
  28.  
  29.           //Preventing the event from continuing
  30.           e.returnValue = false;
  31.           e.cancelBubble = true;
  32.         }
  33.         return false;
  34.       }else{
  35.         if(e.srcElement){
  36.           selectedDefault = e.srcElement;        
  37.         }
  38.       }
  39.  
  40.       return true;
  41.     }
  42.  
  43.  
  44.    // This function is called to set the initial value of the selectedDefault 
  45.     function initializeDefaultSelection(){
  46.       var radioButtons = document.getElementsByName('radio1');
  47.       for(var i=0; i<radioButtons.length; i++)
  48.       { 
  49.         if(radioButtons[i].checked){
  50.          selectedDefault = radioButtons[i];
  51.         }
  52.       }
  53.     }
  54.     </script>
  55.   </head>
  56.   <body>
  57.     <form>
  58.       <input type="radio" name="radio1" id="xRadio" onclick="doClick(event);" />x
  59.       <input type="radio" checked name="radio1" id="yRadio" onclick="doClick(event);" />y
  60.       <input type="radio" name="radio1" id="zRadio" onclick="doClick(event);"/>z
  61.  
  62.       <script type="text/javascript"> 
  63.         try{
  64.           // When the window is loaded, this calls the method that
  65.           // initializes the selectedDefault
  66.           window.attachEvent("onload",initializeDefaultSelection);
  67.         }catch(ex){}
  68.       </script>
  69.     </form>
  70.   </body>
  71. </html>
May 8 '09 #6
Frinavale
9,735 Recognized Expert Moderator Expert
This solution is still not going to help me with my problem though....

It's going to be really ugly if I have to store the default selected radio buttons in an array (more like create a hashtable and store them there)....

Is there a way to add the default selected radio button as a property to the radio buttons? Instead of having to store it in a variable?
May 8 '09 #7

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

Similar topics

0
1183
by: back2grid | last post by:
I'm basically looking for highlighting a datagrid row on selection a radio button control. the problem i'm having is that the event sender(radio btn) i'm getting is functioning as a checkbox. my code is highlighting all rows selected previously. i'm using a metabuilder custom rowselector column and other RB controls that implement grouping. any code would be greatly appreciated
2
1431
by: Scott Natwick | last post by:
I am having trouble validating that a selection has been made from a RadioButton. I created a script to trigger from a CustomValidator, however, it only works when I run the app locally, from the debugger. Once I upload it to the server and run, the script no longer triggers. Any ideas? Thanks in advance,
0
5015
by: Michel Lapointe | last post by:
Hello, I would like to know if there is an event for the Datagridview control that is trigger before the selection change and is cancelable. I'm currently using the SelectionChanged event (using Full Row Select), but this event is trigger only after the selection changed is completed and therefore is non cancelable unless you keep the previous selection in a variable and rechange the selection, which is painful.
4
2109
by: bkasmai | last post by:
On editing textboxes on a webform, when a user tab to a textbox, the text is highlighted or selected. Any accidental key press will remove the original text. This has proved a problem for the users. Is it possible to set a textbox so that the text is not selected when a user tabs to that textbox? Any help on this will be appreciated. BK
6
19745
by: Fnord Nase | last post by:
Hi. We're using the dblclick event in some parts of a web app interface, which works okay, but when a user double clicks on a text element, the browser selects some text before executing the event handler. How can I prevent this behaviour? TIA, nase
3
4272
by: =?Utf-8?B?TWlrZQ==?= | last post by:
Hi Guys, I have a gridview and the first column is a template that generate a radiobuttons in the gridvew. and I would like that user will be able to select one option from the list of the generated radio buttons in my first column - in Client side. (as if in multiple choice exams) Thanks.
1
1342
by: vinnie | last post by:
I placed the following code into my page, but i get an error message, why? The code is: if (this.RadioButtonContatto.Checked == "YES") The error message is: CS0117: 'System.Web.UI.WebControls.RadioButtonList' does not contain a definition for 'Checked'
3
1661
by: Vinnie | last post by:
I placed the following code into my page, but i get an error message, why? The code is: if (this.RadioButtonContatto.Checked == "YES") The error message is: CS0117: 'System.Web.UI.WebControls.RadioButtonList' does not contain a definition for 'Checked'
0
9721
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10635
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
10376
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...
0
10115
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
9198
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
6881
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();...
0
5687
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4332
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
3
3013
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.