Click here to Skip to main content
15,911,030 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have two ASP Controls. One is Text Box and another is ComboBox.

ASP.NET
<asp:TextBox ID="txtName" runat="server"></asp:TextBox>
    <asp:DropDownList ID="ddlCountry" runat="server"></asp:DropDownList>


Now I like to set the value of TextBox and Get the selected index of dropDown list using JavaScript.

How can I do these in Java Script?
Posted

This is JavaScript basics. Here is how you will do it:
Set textbox value -
JavaScript
document.getElementById("txtName").value = "somevalue";

Get the selected index of dropDown -
JavaScript
var index = document.getElementById("ddlCountry").selectedIndex


BTW doing this in jQuery will reduce writing code more. Here's how you do the same thing in jQuery -
JavaScript
$("#txtName").val("somevalue");
var index = $("#ddlCountry").prop("selectedIndex");
 
Share this answer
 
v2
Comments
Jyoti Choudhury 2-Jan-12 5:39am    
but I am not getting value property in the list. I am using JavaScript in ASP.NEt 3.5 and VS2008
Hi, Use below code

For Text Box - Set value
document.getElementById('<%=txtName.ClientID%>').value = "somevalue";

Get the selected index of dropDown

var index = document.getElementById('<%=ddlCountry.ClientID%>').selectedIndex
 
Share this answer
 
v2
Comments
Jyoti Choudhury 2-Jan-12 5:58am    
thanks a lot. but I dont know why, it is not working in VS2008. I am not getting the value property in the list. I tried these solutions but nothing popped out.
XML
<script type="text/javascript">

    function getValue(x)
{
var y= x.value;
document.getElementById('txtName').value =y;

alert(y);
}
    </script>


Use this Script to do work

XML
<asp:TextBox ID="txtName" runat="server"></asp:TextBox>
   <asp:DropDownList ID="ddlCountry"  onchange ="getValue(this);"  runat="server">
   <asp:ListItem >asds</asp:ListItem>
   <asp:ListItem >asrtyrtds</asp:ListItem>
   <asp:ListItem >asyrtyrtyds</asp:ListItem>
   </asp:DropDownList>
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900