View Full Version : asp:dropdownlist getting value with javascript?

09-22-2005, 04:29 PM
Is it possible to reference the .NET asp dropdownlist value and text using javascript on the html page?

I was trying all sorts of variations of things like this w/o luck. Thanks.

var strUser = document.getElementById("dropdown1").value;
var strUser = document.all(dropdown1).children[0].text;

09-22-2005, 05:02 PM
It's a select, not a textbox. Yours would have done okay with a textbox, hidden, or textarea. For select value, you need to use

var e = document.getElementById("dropdown1"); // select element
var strUser = e.options[e.selectedIndex].value;

09-22-2005, 05:30 PM
Thanks...but it's still not getting it. I placed an alert after the first line, and it returns null. Than it bombs out on the bottom line. It's a databound listboxe, don't know if that makes a difference? It's bound on pageload.

var e = document.getElementById("lstUser"); // select element
var strUser = e.options[e.selectedIndex].value;

This is the listbox:
<asp:dropdownlist id="lstUser" runat="server" Height="16px" Width="216px" BackColor="#C0C0FF"></asp:dropdownlist>

09-22-2005, 05:38 PM
Ah, yeah, .net changes control names for some things. I'm still learning about that.
You need to register a script block server side and use control.ClientID.

Here's what I use in my datagrid_edit command handler to set focus.

// set focus to textbox so people don't have to scroll
TextBox txtBox = (TextBox) this.dgRptSpecs.Items[e.Item.ItemIndex].Cells[1].FindControl("rptNameTxt");
RegisterStartupScript("focus", "<script type=\"text/javascript\">\n"+
"Form1." + txtBox.ClientID + ".focus();\n" +
"<" + "/script>");

09-22-2005, 05:46 PM
Ahhh.....I remember this from before now. .NET changes the client ID. I did vew source on the web page and see that the ID has been changed to "_ctl0_lstUser". When I plugged that in, it works fine.

Thanks for jogging my memory!

09-22-2005, 07:10 PM
No problem, but be careful.
It may be dynamically assigned an a per run basis. I'm not sure. I'd check into that before counting on it.