Let your TextBox's ID is "
TextBox1", the following JS retrieve the text of the TextBox:
- // tested with IE7 and FF3 only
-
var txt = document.getElementById("TextBox1");
-
var s1 = txt.value;
Let your DropDownList's ID is "
DropDownList1", the following JS retrieve the selected item's value:
- // tested with IE7 and FF3 only
-
var ddl = document.getElementById("DropDownList1");
-
var s2 = lst.value;
Somehow, that's no direct access to the selected item's text. Or, you can use the following JS to retrieve the selected item, then further down to its value / text:
-
// tested with IE7 and FF3 only
-
var ddl = document.getElementById("DropDownList1");
-
var i = ddl.selectedIndex;
-
var s3 = ddl.options[i].value;
-
var s4 = ddl.options[i].text;
When you combine the JS codes and make them work with your ASP.NET page, you should be careful since the
Control ID is not promised to be same with the
Client ID (the coming ASP.NET 4.0 allows us to fix the Client ID, luckily).
Let say: I have a TextBox named "
TextBox1" and a DropDownList named "
DropDownList1". I would like to have the TextBox's text and the DropDownList's selected item's text and value to be concatenated and being shown through a JS alert box when a Button named "
Button1" is clicked.
1. Add a JS function to the .aspx file - ...
-
// Client IDs of the TextBox and DropDownList are passed as parameters
-
// Use meaningful variable names for your case
-
function showResult(txtID, ddlID)
-
{
-
var txt = document.getElementById(txtID);
-
var ddl = document.getElementById(ddlID);
-
var i = ddl.selectedIndex;
-
-
var s1 = txt.value;
-
var s2 = ddl.options[i].text;
-
var s3 = ddl.options[i].value;
-
-
var result = s1 + " " + s2 + " " + s3;
-
alert(result);
-
}
-
...
2. Attach the JS function call the the Button is .cs file - ...
-
protected void Page_Load(object sender, EventArgs e)
-
{
-
if (!Page.IsPostBack)
-
{
-
Button1.Attributes["onclick"] = string.Format(
-
"showResult('{0}', '{1}'); return false;", TextBox1.ClientID, DropDownList1.ClientID);
-
// Or set its OnClientClick property
-
}
-
}
-
...
The following C# codes is equivalent if you don't like to use string.Format():
- ...
-
Button1.Attributes["onclick"] =
-
"showResult('" + TextBox1.ClientID + "', '" + DropDownList1.ClientID + "'); return false;";
-
...
Different scenarios, different solutions. Hope this can give you some ideas.