ASP.NET 4.0 - Accessing Server Controls in Javascript

I'm currently converting a web site developed in ASP.NET 2.5 (VB.NET Code) to ASP.NET 4.0 (VB.NET code).

The problem I'm having (that I did not expect) is accessing server side controls through Javascript.

I have an Textbox and ListBox server controls on the web page.

<asp:ListBox ID="lstStore" runat="server"></asp:ListBox>
<asp:TextBox ID="txtCriteria" runat="server">

The following Javascript works in the ASP.NET 2.5 Web Site:

var list = document.getElementById("lstStore");
var txtCriteria = document.getElementById("txtCriteria");

alert(txtCriteria.value);
alert(list.options.length);

The javascript error I get is "Unable to get the value of the property 'value' on the text box" and "Unable to get the value of the property 'Options' on the list box.

Has something changed with ASP.NET 4.0?  Note:  I do not get any errors on the two 'var' statements.  It is properly identifying the controls on the client side.
tfewster500Asked:
Who is Participating?
 
leakim971PluritechnicianCommented:
try :

var list = document.getElementById("<%= lstStore.ClientID %>");
var txtCriteria = document.getElementById("<%= txtCriteria.ClientID %>");

alert(txtCriteria.value);
alert(list.options.length);

http://weblogs.asp.net/asptest/archive/2009/01/06/asp-net-4-0-clientid-overview.aspx
0
 
tfewster500Author Commented:
Sorry, typo in my sample code.  I am propertly closing the text box tag

<asp:ListBox ID="lstStore" runat="server"></asp:ListBox>
<asp:TextBox ID="txtCriteria" runat="server">"></asp:TextBox>

0
 
kovilpattiBaluCommented:
One thing is your control name should ne within single quotes.
ie:
var list = document.getElementById('lstStore');
var txtCriteria = document.getElementById('txtCriteria');

Second thing is you can use HTML control name of both lstStore and txtCriteria.
[HTML control name you can get it from view source]
0
 
tfewster500Author Commented:
Awesome this worked.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.