I would like to read selected value from dropdownlist and accordingly, set the maxlength of a textbox through javascript.

To use javascript inside a user control, one should remember, while it is rendered in the page, a control called txtComany will be having a name like ctl03$txtComany when it is rendered on the page.

Hence it is important to call the clientId of the textbox like :

document.getElementById(“<%=txtComany.ClientID%>”).value;

 

function SetTextBoxMaxLength() {
var e = document.getElementById(“<%=DropDownlist1.ClientID%>);
var strUser = e.options[e.selectedIndex].text;
if (strUser == “Cargo ” || strUser == “Agent”) {
//Set maxlength of textbox to 11 through Javascript
document.getElementById(“<%=TextBox1.ClientID%>).maxLength = 11
}
else {
//Set maxlength of textbox to 8 through Javascript
document.getElementById(“<%=TextBox1.ClientID%>).maxLength = 8
}
}

The HTML of the page is like

<asp:TextBox CssClass=”contact” ID=”CUECode” onKeyDown=”SetCUECodeMaxLength();” runat=”server”/> 

To get selected value from dropdownlist using javascript:

var e = document.getElementById(“<%=Dropdown1.ClientID%>”);

var strUser = e.options[e.selectedIndex].text;

 To use onchange event of dropdownlist instead of using the selectedindexchange event through code behind to prevent postback, suppose the HTML is as shown below:

<asp:DropDownList ID=”DropDown1″ runat=”server” onchange=”ClearTextBox();” class=”type”/>

function ClearTextBox() {

  

 if (document.getElementById(“<%=TextBox1.ClientID%>”).value.length > 0) {

 

document.getElementById(“<%=TextBox1.ClientID%>”).value = “”;

}

}