Radiobutton enables textbox

Posted on 2004-11-29
Last Modified: 2012-06-21
I have the following code in my form:

      <asp:radiobuttonlist id="Shape" repeatcolumns="4" runat="server" font="arial,helvetica" font-size="10pt">
      </asp:radiobuttonlist><asp:requiredfieldvalidator id="ShapeRequired" controltovalidate="Shape" errormessage="Vul aub een vorm in!" runat="server">*</asp:requiredfieldvalidator><br>
                <asp:Label id="LabelOther" font="Arial,Helvetica" text="Other" runat="server"/><br>
      <asp:textbox id="Other" tooltip="Welke overige vorm wilt u gebruiken?" runat="server"/>

All I want to do is that the radiobutton "Overig" will enable the textbox Other so users can fill out info.
If you dont select "Overig" the textbox Other should remain invisible.

In ASP i solved this with javascript, how do you make this work in
Thanx a whole lot for your help already :)

Question by:fryslan
    LVL 3

    Accepted Solution

    One way to go about doing it without using javascript-->

    1. In the design view, set the AutoPostBack attribute of "Shape" to TRUE
    2. In the design view, set the Enabled attribute of "Other" to FALSE
    3. Add the following code to you codebehind page...

    Private Sub Shape_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Shape.SelectedIndexChanged
             If Shape.SelectedItem = "Overig" Then
                   Other.Enabled = TRUE
                   Other.Enabled = FALSE
            End If
    End Sub

    You may see the page flicker when a radio button is selected, this is due to the fact that this logic is being handled on the server side, thus the page is getting reloaded. You can add SmartNavigation="True" to your <%@ Page %> declaration atop your ASPX page and that will eliminate that issue.
    LVL 7

    Assisted Solution

    The way above is not incorrect but causes a postback which is pretty pointless just to do one little change, so this can be done with Javascript but unfortunately you won't be able to do this with the RadioButtonList control, it doesn't support adding javascript attributes to it anything in its items collection only to the main control itself so this is how you would do it:

    This would be in your HTML View
                      <script language="javascript">
          function toggletxt(b_disable){
                var objOther = document.getElementById("txtOther");
                if (!b_disable) objOther.focus();

                      <asp:RadioButton id="rdoVierkant" runat="server" Text="Vierkant" GroupName="Shape" Checked="True"></asp:RadioButton>
                      <asp:RadioButton id="rdoRechthoek" runat="server" Text="Rechthoek" GroupName="Shape"></asp:RadioButton>
                      <asp:RadioButton id="rdoCirkel" runat="server" Text="Cirkel" GroupName="Shape"></asp:RadioButton>
                      <asp:RadioButton id="rdoOverige" runat="server" Text="Overige" GroupName="Shape"></asp:RadioButton><br>
                      <asp:Label id="LabelOther" font="Arial,Helvetica" text="Other" runat="server" /><br>
                      <asp:textbox id="txtOther" tooltip="Welke overige vorm wilt u gebruiken?" runat="server" Enabled="False" />

    And in your Codebehind it would be:

    Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
            'Put user code to initialize the page here
            rdoOverige.Attributes.Add("onclick", "toggletxt(false);")
    'on the other buttons you can put this
    rdoCirkel.Attributes.Add("onclick", "toggletxt(true);")

    End Sub

    LVL 9

    Expert Comment


    Although both methods work just fine, there are pros and cons to everything.  You have to weigh it out and decide for yourself.

    smolam's does not require a round trip, but it is dependant on the visitors browser, browser version, and needs JavaScript enabled for it to work.

    The first answer is what I suggest to you (no offense smolam) because the round trip can often be transparent to the visitor.  It is often not even an issue.  However, it is not dependant on anything except your abilities.  It is completely out of the hands of the visitor.  It will work in all browsers all the time (as long as your site is up - hehehe).

    Author Comment

    Ok thanx all you guys, I will mess around with it and then split up the points :P
    Thanx very much for your very usefull and fast replies....
    You just gotta love EE :)

    Author Comment


    One question
    Im trying to implement your code
    And it says: "Voor de koppelingscomponent is een WithEvents-variabele vereist."
    In English: "For this ....component a WithEvents variable is required."

    So I have to declare a variable?
    Sorry im so new to this stuff, I feel such a noob :(
    LVL 3

    Expert Comment

    It looks like it is requireing one of your controls and/or variables to be declared 'WithEvents'. From what you have shown me, I cannot determine which variable declaration needs that addition, but it is only a matter of adding 'WithEvents' into the vaiable declaration...

    For example, you would change...
    Dim bttn_Submit as System.Web.UI.WebControls.Button
    Protected WithEvents bttn_Submit as System.Web.UI.WebControls.Button

    You want to be sure to include WithEvents on all your declarations where you are creating an object that can raise events, such as Click, or IndexChange, and so on... Controls added from the design view should already have this in the decalration, check through any other controls you may have added manually in your codebehind.

    Author Comment

    All the form elements have already been declared (thats atleast what I get when I try to declare one.
    Can you have a look at my full source here below and maybe you can see the problem? TIA!!!!


    <%@ Page Explicit="True" Language="VB" Debug="True" SmartNavigation="True" %>
    <%@ Import Namespace="System.Data" %>
    <%@ Import Namespace="System.Data.OleDb" %>
    <%@ Register TagPrefix="UserControl1" TagName="Top" Src="usercontrols/uc_top.ascx" %>
    <%@ Register TagPrefix="UserControl2" TagName="BarTop" Src="usercontrols/uc_bar_top.ascx" %>
    <%@ Register TagPrefix="UserControl3" TagName="MenuTop" Src="usercontrols/uc_menu_top.ascx" %>
    <%@ Register TagPrefix="UserControl4" TagName="MenuLeft" Src="usercontrols/uc_menu_left.ascx" %>
    <%@ Register TagPrefix="UserControl5" TagName="Bottom" Src="usercontrols/uc_bottom.ascx" %>
    <UserControl1:Top runat="server" />
    <UserControl2:BarTop runat="server" />
    <UserControl3:MenuTop runat="server" />
    <UserControl4:MenuLeft runat="server" />

    <Script Language="VB" Runat="server">
        Sub SendEmailButton_Click(Sender As Object, E As EventArgs)
           If IsValid = True Then
                      ' Send E-mail :)
           End If
        End Sub

          Private Sub Shape_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles rblShape.SelectedIndexChanged
                       If rblShape.SelectedItem = "Overige" Then
                               txtOther.Enabled = TRUE
                               txtOther.Enabled = FALSE
                      End If
          End Sub

    <Div Id="content-center">
        <form runat="server">
          <asp:radiobuttonlist id="rblShape" autopostback="True" repeatcolumns="4" font="arial,helvetica" font-size="10pt" runat="server">
          </asp:radiobuttonlist><asp:requiredfieldvalidator id="reqShape" controltovalidate="rblShape" errormessage="Vul aub een vorm in!" runat="server">*</asp:requiredfieldvalidator><br>
        <asp:textbox id="txtOther" tooltip="Welke overige vorm wilt u gebruiken?" enabled="False" runat="server"/><br>
          <asp:validationsummary id="sumValidation" displaymode="bulletlist" headertext="De volgende fouten zijn geconstateerd in uw invoer:" runat="server"/>
        <asp:Label id="lblName" font="Arial,Helvetica" text="Naam" runat="server"/><br>
          <asp:textbox id="txtName" tooltip="Type hier uw naam" runat="server"/>
        <asp:requiredfieldvalidator id="reqName" controltovalidate="txtName" errormessage="Vul aub uw naam in!" runat="server">*</asp:requiredfieldvalidator><br>
        <asp:Label id="lblAddress" font="Arial,Helvetica" text="Adres" runat="server"/><br>
        <asp:textbox id="txtAddress" tooltip="Type hier uw adres" runat="server"/>
        <asp:requiredfieldvalidator id="reqAddress" controltovalidate="txtAddress" errormessage="Vul aub uw adres in!" runat="server">*</asp:requiredfieldvalidator><br>
        <asp:Label id="lblPC6" font="Arial,Helvetica" text="Postcode" runat="server"/><br>
        <asp:textbox id="txtPC6" tooltip="Type hier uw postcode" runat="server"/>
        <asp:requiredfieldvalidator id="reqPC6" controltovalidate="txtPC6" errormessage="Vul aub uw postcode in!" runat="server">*</asp:requiredfieldvalidator><asp:regularexpressionvalidator id="regPC6" controltovalidate="txtPC6" validationexpression="^[1-9]{1}[0-9]{3}\s{0,1}?[a-zA-Z]{2}$" errormessage="Voer een geldige postcode in!" runat="server">*</asp:regularexpressionvalidator><br>
        <asp:Label id="lblCity" font="Arial,Helvetica" text="Woonplaats" runat="server"/><br>
        <asp:textbox id="txtCity" tooltip="Type hier uw woonplaats" runat="server"/>
        <asp:requiredfieldvalidator id="reqCity" controltovalidate="txtCity" errormessage="Vul aub uw woonplaats in!" runat="server">*</asp:requiredfieldvalidator><br>
        <asp:Label id="lblPhone" font="Arial,Helvetica" text="Telefoonnummer" runat="server"/><br>
        <asp:textbox id="txtPhone" tooltip="Type hier uw telefoonnummer" runat="server"/>
        <asp:requiredfieldvalidator id="reqPhone" controltovalidate="txtPhone" errormessage="Vul aub uw telefoonnummer in!" runat="server">*</asp:requiredfieldvalidator><asp:regularexpressionvalidator id="regPhone" controltovalidate="txtPhone" validationexpression="([0]{1}[6]{1}[-\s]*([1-9]{1}[\s]*){8})|([0]{1}[1-9]{1}[0-9]{1}[0-9]{1}[-\s]*([1-9]{1}[\s]*){6})|([0]{1}[1-9]{1}[0-9]{1}[-\s]*([1-9]{1}[\s]*){7})" errormessage="Voer een geldig 10 cijferig telefoonnummer in!" runat="server">*</asp:regularexpressionvalidator><br>
        <asp:Label id="lblEmail" font="Arial,Helvetica" text="Email" runat="server"/><br>
        <asp:textbox id="txtEmail" tooltip="Type hier uw e-mail adres" runat="server"/>
        <asp:requiredfieldvalidator id="reqEmail" controltovalidate="txtEmail" errormessage="Vul aub uw emailadres in!" runat="server">*</asp:requiredfieldvalidator><asp:regularexpressionvalidator id="regEmail" controltovalidate="txtEmail" validationexpression="^((?:(?:(?:\w[\.\-\+]?)*)\w)+)\@((?:(?:(?:\w[\.\-\+]?){0,62})\w)+)\.(\w{2,6})$" errormessage="Voer een geldig e-mail adres in!" runat="server">*</asp:regularexpressionvalidator><br>
        <asp:Label id="lblRemarks" font="Arial,Helvetica" text="Opmerkingen" runat="server"/><br>
        <asp:textbox id="txtRemarks" tooltip="Type hier uw vragen/opmerkingen" textmode="multiline" runat="server"/><br><br>
        <asp:button id="btnVersturen" text="Versturen" runat="server"></asp:button>

    <UserControl5:Bottom runat="server" />

    LVL 3

    Expert Comment

    In the line that places the radiobuttonlist on the page(<asp:radiobuttonlist id="rblShape"..... ), add
    OnSelectedIndexChanged="Shape_SelectedIndexChanged". You can get rid of "Handles rblShape.SelectedIndexChanged
    " from the function definition. Also, change "If rblShape.SelectedItem = "Overige" Then" to "If rblShape.SelectedVALUE = "Overige" Then".

    hope this works out for you!

    Author Comment


    That totally works, im so happy, changed the txtOther.Enable to txtOther.Visible = False etc. but that was so simple even I got it ;-)

    So one last question
    (can i actually give you bonus points? :P)
    How do I enable the form check for the txtOther field only when its visible, and not when its invisible?
    If you could tell me this I would be fine with finishing the form for the rest myself.....

    Much obliged!!! :)))
    LVL 3

    Expert Comment

    If you want to have validation on the txtOther field, then just add your validator in the design view like you did for the otehr fields. If the txtOther field is not visible, the validator for it will not be active... it will only be active when you have that field set as visible. There is nothing extra you would need to do. FYI, you can programmaticlly enable and disable individual validators just as you would text fields (example:reqName.Enabled = FALSE). Also, you can shut down validation entirely by setting the CausesValidation property of the button to FALSE. You wont need to do any of that if I understand you correctly, but just so you know...

    Author Comment

    Thanx m8, you really helped me out here, I think I can manage to setup the forms from now on.... :)
    I still have lots to learn when it comes to ASP.NET but I finally see the advantages of it now full blown, now I just have to absorb ASP.NET knowledge but my brain is too full ;-)

    THANX AGAIN :)))))

    Write Comment

    Please enter a first name

    Please enter a last name

    We will never share this with anyone.

    Featured Post

    What Security Threats Are You Missing?

    Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

    I have developed many web applications with asp & and to add and use a dropdownlist was always a very simple task, but with the new, setting the value is a bit tricky and its not similar to the old traditional method. So in this a…
    Today is the age of broadband.  More and more people are going this route determined to experience the web and it’s multitude of services as quickly and painlessly as possible. Coupled with the move to broadband, people are experiencing the web via …
    Need more eyes on your posted question? Go ahead and follow the quick steps in this video to learn how to Request Attention to your question. *Log into your Experts Exchange account *Find the question you want to Request Attention for *Go to the e…
    how to add IIS SMTP to handle application/Scanner relays into office 365.

    761 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

    14 Experts available now in Live!

    Get 1:1 Help Now