How can I do to set the minimum and maximum value of a textbox according to what I select from a dropdownlist? Suppose I have a dropdownlist with 3 items. If I choose the first item, the textbox should have a minimum of 3 letters and a maximum of 6. If I choose the second item, the textbox should have a minimum of 4 letters and a maximum of 8. I was wondering if there is a feasible way to do everything on the client side using the onChange event on the dropdownlist and a rangevalidator for the textbox. The idea would be that in the onChange event it validates which item was selected and that it sets the min and max of the rangevalidator. How could I implement this?
<asp:TextBox ID="TextBox" MaxLength="10" runat="server"></asp:TextBox>
<asp:DropDownList ID="DropDownList" runat="server"></asp:DropDownList>
In the code fill the dropdownlist with a datatable (db data) and add the attribute to the dropdownlist of onchange and to the textbox of onkey
DropDownList.Attributes.Add("OnChange", "cambiartextboxlength();")
TextBox.Attributes.Add("OnKeyup", "verificarvaloringresado();")
JavaScript functions
function cambiartextboxlength()
{
var textbox=document.getElementById('<%=TextBox.ClientID%>');
var ddl=document.getElementById('<%=DropDownList.ClientID%>');
var
if (ddl.selectedIndex == 0)
{
textbox.maxLength=*sacarvalordelappsettings*;
}else if (ddl.selectedIndex == 1){
textbox.maxLength=*sacarvalordelappsettings*;
}else if (ddl.selectedIndex == 2) {
textbox.maxLength=*sacarvalordelappsettings*;
}
}
function verificarvaloringresado()
{
var textbox=document.getElementById('<%=TextBox.ClientID%>');
if (textbox.value.length != textbox.maxlength) {
alert('El valor ingresado no es correcto!');
}
}
We add the EventListener to the list
change
to execute a function when the user selects an element from the list.That function gets the value that the user has selected. Since they are really 2 values separated by commas, we use
split
to create aArray
with those 2 values.Finally we add the corresponding attributes to the
input
with the values of theArray
.