Solved

How to make OnClientClick event for Radio List

Posted on 2011-09-06
15
2,154 Views
Last Modified: 2012-05-12
I have a group of radio buttons defined as below. I'm trying to add OnClientClick event for each radio button, but it won't work at all. It seems that the radio button list does not have a OnClientClick event. How can I make a handler for OnClientClick on each radio button? I only need to make hide fields show. Thanks.

<asp:Panel ID="pldev" runat="server" GroupingText="Choose a Type" Width="370px">
&nbsp;<asp:RadioButton id="type1" Text="Pager" GroupName="device" AutoPostBack="true" OnCheckedChanged="DevSelected" runat="server" />
&nbsp;<asp:RadioButton id="type2" Text="Cell Phone" GroupName="device" AutoPostBack="true" OnCheckedChanged="DevSelected" runat="server" />
&nbsp;<asp:RadioButton id="type3" Text="Landline" GroupName="device" AutoPostBack="true" OnCheckedChanged="DevSelected" runat="server" />
&nbsp;<asp:RadioButton id="type4" Text="Air Card" GroupName="device" AutoPostBack="true" OnCheckedChanged="DevSelected" runat="server" />
</asp:Panel>
0
Comment
Question by:minglelinch
  • 9
  • 5
15 Comments
 
LVL 16

Expert Comment

by:disrupt
ID: 36491575
0
 
LVL 7

Expert Comment

by:Gewgala
ID: 36491668
If you have AutoPostBack set to true, you can do:

protected void DevSelected(object sender, EventArgs e)
{
      var radioButton = sender as RadioButton;

      var checked = radioButton.Checked;

      StringBuilder sb = new StringBuilder();

      sb.AppendLine("<script type=\"text/javascript\">");  

      if (radioButton.Text == "Pager")
           sb.AppendLine("pagerFunction();");
      else if (radioButton.Text == "Cell Phone")
           sb.AppendLine("cellPhoneFunction();");
      else if (etc...) { ... }

      sb.AppendLine("</script>");

      ClientScript.RegisterStartupScript(Page.GetType(), "rbOptions", sb.ToString());
}

Open in new window


That will cause the client side javascript code you have to be executed AFTER the server side code is processed, but it will be executed still.  You would just need to change the "pagerFunction()" and "cellPhoneFunction()" calls to what you need.  And of course, if your client side code takes parameters, you can do that too:  "pagerFunction(1);" (for an Id of 1, etc) or concatenate in a variable value like:

sb.AppendLine("myFunction(" + myId + ");");

Hope this helps.
0
 
LVL 7

Expert Comment

by:Gewgala
ID: 36491681
Are you using some form of AJAX?  Because if you are, my above example will have to be modified to accomodate but the same idea would apply.  Are you using AJAX?  If so, which kind, asp.net ajax, or telerik, or some other provider?
0
 
LVL 7

Expert Comment

by:Gewgala
ID: 36491827
But hold on, I just remembered you can do this:

<asp:RadioButton ID="type1" Text="Pager" GroupName="device" AutoPostBack="true" OnCheckedChanged="DevSelected" runat="server" onclick="someFunction(this)" />

If you have a javascript function like this accessible in the scope of your radio button:

function someFunction(obj)
{
     var id = obj.value;
     var checked = obj.checked;

     alert("Is " + id + " checked?: " + checked);
}

Open in new window


In this example, if the user clicks on the RadioButton, it will display an alert:   "Is type1 checked?: true"

You can use the ID values in your javascript function to determine which radio button is checked, such as sniffing for type1 or type2 or type3 etc, whatever you assign to your ID properties of each RadioButton.  The reason why just putting in a "onclick" works in the RadioButton definition, is because ASP.NET will render that exact text on the ACTUAL HTML element RadioButton list that is written out to the page.  You CAN have an "onclick" in that regard because that IS the actual client javascript event that is attachable to a radio button.

Either this example or the first one I posted that goes to the Server first and then outputs the call to the client side code will work.  This one may be more in line with what you were looking for though.

0
 
LVL 1

Author Comment

by:minglelinch
ID: 36495748
Thank you all for the comments. All of your answers worked for popping up a confirm box by using OnClick. But it does not work like onClientClick, as the server side function OnCheckedChanged is still executed although Cancel/No of the confirm box is chosen.

How can I code it to achieve my purpose ?
I need if false is return from OnClick, the server function OnCheckedChanged should not be executed. If true is returned from OnClick, the server function OnCheckedChanged will be executed.

Thanks.
0
 
LVL 7

Expert Comment

by:Gewgala
ID: 36496847
Add the event parameter to the onclick function in the radio button declaration like so:

<asp:RadioButton ID="type1" Text="Pager" GroupName="device" AutoPostBack="true" OnCheckedChanged="DevSelected" runat="server" onclick="someFunction(this, event)" />

Then, in your JavaScript function, put this in:

function someFunction(obj, e)
{
     var id = obj.value;
     var checked = obj.checked;

     alert("Is " + id + " checked?: " + checked);

     if (e.preventDefault)          // <-- add in this if/else block
          e.preventDefault();       // <-- this line is for non-IE browsers
     else
          e.returnValue = false;   // <-- this line is for IE browsers
}

Open in new window


This should tell the browser to stop normal server side execution of the radio button list that was clicked.
0
 
LVL 7

Expert Comment

by:Gewgala
ID: 36496859
I forgot to specifically point out in the previous post, that you need to also put in the e parameter in the java script function declaration, to be used by the new if/else block at the end of the function.
0
Better Security Awareness With Threat Intelligence

See how one of the leading financial services organizations uses Recorded Future as part of a holistic threat intelligence program to promote security awareness and proactively and efficiently identify threats.

 
LVL 1

Author Comment

by:minglelinch
ID: 36498546
Thank you, Gewqala. With your code above, I have made a progress but still a little bug need fixing.

I followed and I did:
<asp:RadioButton ID="type1" Text="Pager" GroupName="device" AutoPostBack="true" OnCheckedChanged="DevSelected" runat="server" onclick="someFunction(this, event)" />

  function SwitchClick(obj, e)
  {
         var id = obj.value;
         var checked = obj.checked;
         if(!confirm("Are you sure you want to make a switch and ignore data on this page?"))
         {
             if (e.preventDefault)          // <-- add in this if/else block
                  e.preventDefault();       // <-- this line is for non-IE browsers
             else
                  e.returnValue = false;   // <-- this line is for IE browsers
         }
    }

If I click OK of the confirm box,  it works as expected: The new selected radio button is selected and the new data fields (new page) is displayed.
However, if I click Cancel of the confirm box, the data fields (the page) keep same which is expected, but all radio buttons are unselected, including the one previous selected. I would like the radio button previous selected is still selected. As the previous data fields/page stay and the previous radio button should still be selected.

How can achieve it? Thanks.
0
 
LVL 7

Expert Comment

by:Gewgala
ID: 36499271
What does your Cancel button do exactly?  Does it execute server-side code?  If that is the case, it sounds like what's happening is that because you have prevented code from executing on the server when the RadioButton is selected, the server still thinks that it is unselected and thus does not populate the radio button selection.

What I would do if I'm understanding your scenario correctly, is add in a hidden field that holds values of radio buttons that have been selected.  For example:

<asp:HiddenField ID="hfSelections" runat="server" />

Open in new window


And then in your JavaScript function, you can do this:

function SwitchClick(obj, e)
  {
         var id = obj.value;
         var checked = obj.checked;
         if(!confirm("Are you sure you want to make a switch and ignore data on this page?"))
         {
             // persist selections:
             var hf = document.getElementById("hfSelections");
             if (hf)
             {
                  if (checked)
                  {
                        hf.value = id;
                  }
                  else
                  {
                        hf.value = "";
                  }
             }

             if (e.preventDefault)          // <-- add in this if/else block
                  e.preventDefault();       // <-- this line is for non-IE browsers
             else
                  e.returnValue = false;   // <-- this line is for IE browsers
         }
    }

Open in new window


Then, when you handle the Cancel button click code on the server, you just look at the text value of hfSelections and see if it's populated.  If it is, then you grab that value, figure out which RadioButton ID is in it, and then say:

if (hfSelections.Value == "type1")
    type1.Checked = true;
else if (hfSelections.Value == "type2")
    type2.Checked = true;

Open in new window


etc...

Then after that still on the server you would want to clear the value of hfSelections:

hfSelections.Value = string.Empty;

Open in new window


By doing this, you are persisting which selection was made between post backs even though the actual selection of the RadioButton didn't make it to the server by using the HiddenField.  

Does that help?
0
 
LVL 1

Author Comment

by:minglelinch
ID: 36502820
Thanks for your help, which gave me the HiddenField usage.

Cancel button do nothing except preventing server code from executing and keep the same thing on the page, including the radio button previously selected. When the code execution have gone into SwitchClick function, the previous selected radiobutton is already unselected and clicked radiobutton is selected. The Cancel button needs to have to recove the previous selected button still selected insteadu of the newly clicked one selected.

It is a good idea to use a HiddenField to hold the previous selected radiobutton, but how and when to assign its value?

Now the default is that none radiobutton is selected at the first loading, and no data field is displayed. Since the first radiobutton selection, there always have been a radiobutton selected and the corresponding fields dispalyed. Let's say 'type1' has been selected. Now clicking type2 button, the execution goes into SwitchClick. At this time, the type2 radio button has already selected and type1 is unselected. If the hiddenfield holds the previous selected button type1, and when Cancel is chosen, the type1 button can be recovered to be selected again instead of type2 selection.

So how can the hiddenfield get the selected button? Is it possible to make a radio button selection in javascript? Thanks.

0
 
LVL 7

Expert Comment

by:Gewgala
ID: 36503427
Ok, I think I'm getting closer to understanding what you need :)  In the below example I've introduced a "lastRadio" variable on a member-level scope outside of the function which I renamed from SwitchClick to RadioClick.  This function needs to be called every time a radio buttin is clicked (not just when it's a different selection).  It preserves the last checked radio button in memory in the lastRadio variable.  It is then used to recover the previous selection made.

var lastRadio = null;

function RadioClick(obj, e)
  {
         var id = obj.value;
         var checked = obj.checked;

         if (!lastRadio)
             lastRadio = obj;
         
         if (lastRadio.id != id)
         {
               if(!confirm("Are you sure you want to make a switch and ignore data on this page?"))
               {
                   // revert back to previous selection:
                   lastRadio.checked = true;

                   if (e.preventDefault)          // <-- add in this if/else block
                        e.preventDefault();       // <-- this line is for non-IE browsers
                   else
                        e.returnValue = false;   // <-- this line is for IE browsers
               }
               else
                   lastRadio = obj;  // make the current selection the lastRadio obj because the user confirmed they want the new selection
         }
    }

Open in new window


Let me know if I can better modify it for your needs but hopefully this makes sense.
0
 
LVL 1

Author Comment

by:minglelinch
ID: 36505041
Thank you, Gewgala. It's more closer now but still a tep away. It's still none selected. I think it's required to add extra code lines to set other three radiobuttons to false after lastRadio.checked = true.
However it's hard to find the other three.
0
 
LVL 7

Accepted Solution

by:
Gewgala earned 500 total points
ID: 36505108
The below modifications will make it so the last radio button is checked and will make sure the others are not checked.

var lastRadio = null;

function RadioClick(obj, e)
  {
         var id = obj.value;
         var checked = obj.checked;

         if (!lastRadio)
             lastRadio = obj;
         
         if (lastRadio.id != id)
         {
               if(!confirm("Are you sure you want to make a switch and ignore data on this page?"))
               {
                   // revert back to previous selection
                   // and make sure the other radio buttons are not checked
                   // at the same time with the following loop.
                   // Because there are only 4 radio items, we'll loop through them
                   // one by one and make sure the last one is checked and the others are not.

                   for (var x = 1; x <= 4; x++)
                   {
                        var radioId = "type" + x;

                        var radioButton = document.getElementById(radioId);

                        if (radioId == lastRadio.value)
                            radioButton.checked = true;
                        else
                            radioButton.checked = false;
                   }

                   if (e.preventDefault)          // <-- add in this if/else block
                        e.preventDefault();       // <-- this line is for non-IE browsers
                   else
                        e.returnValue = false;   // <-- this line is for IE browsers
               }
               else
                   lastRadio = obj;  // make the current selection the lastRadio obj because the user confirmed they want the new selection
         }
    }

Open in new window

0
 
LVL 1

Author Closing Comment

by:minglelinch
ID: 36505657
Thanks, that works.
0
 
LVL 7

Expert Comment

by:Gewgala
ID: 36505664
Glad I could help ;)
0

Featured Post

How to improve team productivity

Quip adds documents, spreadsheets, and tasklists to your Slack experience
- Elevate ideas to Quip docs
- Share Quip docs in Slack
- Get notified of changes to your docs
- Available on iOS/Android/Desktop/Web
- Online/Offline

Join & Write a Comment

Many of us here at EE write code. Many of us write exceptional code; just as many of us write exception-prone code. As we all should know, exceptions are a mechanism for handling errors which are typically out of our control. From database errors, t…
Real-time is more about the business, not the technology. In day-to-day life, to make real-time decisions like buying or investing, business needs the latest information(e.g. Gold Rate/Stock Rate). Unlike traditional days, you need not wait for a fe…
This video shows how to remove a single email address from the Outlook 2010 Auto Suggestion memory. NOTE: For Outlook 2016 and 2013 perform the exact same steps. Open a new email: Click the New email button in Outlook. Start typing the address: …
This tutorial demonstrates a quick way of adding group price to multiple Magento products.

706 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

17 Experts available now in Live!

Get 1:1 Help Now