Set min and max to TextBox depending on item selected from DropDownList? RRS feed

  • Question

  • User-2037392709 posted

    Is there a way from client side to change a TextBox min and max length and validate like rangevalidator, depending on item selected from a dropdownlist?
    Lets say I select the first element from the dropdownlist, the textbox min and max value has to be 2 and 4 and the max length 4. I was thinking on using RangeValidator and also onChange event? Any solution/recommendation to implement this? Something like this:

    <asp:DropDownList ID="DropDownList1" runat="server"></asp:DropDownList>
    <asp:TextBox ID="TextBox1" MaxLength="4" runat="server"></asp:TextBox>
    <asp:RangeValidator ID="RangeValidator1" runat="server"
    ControlToValidate="TextBox1" ErrorMessage="Insert correct value."
    MinimumValue="2" MaximumValue="4" Type="Integer"></asp:CompareValidator>
    Populated dropdownlist.
    DropDownList1.Attributes.Add("OnChange", "ChangeRangeValidatorValues();")
    'Javascript function
            function indexChanged()
                var textbox=document.getElementById('<%=TextBox1.ClientID%>');
                var droplist=document.getElementById('<%=DropDownList1.ClientID%>');
                var rangevalidator=document.getElementById('<%=RangeValidator1.ClientID%>');
            if (droplist.selectedIndex == 0)
                rangevalidator.minimumvalue=<%=ConfigurationManager.AppSettings["someValue"] %>;
            }else if (ddl.selectedIndex == 1){
            }else if (ddl.selectedIndex == 2) {
    Friday, April 27, 2018 4:20 AM


  • User1724605321 posted

    Hi Fabiannn,

    One way is directly use javascript to control the behaviors of your dropdownlist and textbox ,  bind onchange event to your dropdownlist :

    $('#YourDropDownList').on('change', function () {}

    And base on the selection dynamically set the attribute of your testbox(or store the values in hidden field) . And of course you need to check the values using javascript in keyup event of the textebox  :$('#yourtextbox').on('keyup', function (e) {} .

    The other solution is set the min and max value of RangeValidator in dropdownlist's onchange server side function , but this way doesn't use javascript functions.

    Best Regards,

    Nan Yu

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Saturday, April 28, 2018 5:14 AM