Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading ASP.NET text box value with JavaScript

I am using a ASP.NET(3.5) page and I have a text box called txtName.

I want to read the value with JavaScript like so but it does not work.

var Name = document.getElementById(txtName).value;
alert(Name);

Even this does not want to work:

var Name = document.FormName.txtName.Value;
alert(Name);

This work with plain HTML pages but not with my ASP.NET page, why?

like image 737
Etienne Avatar asked Jul 21 '10 11:07

Etienne


1 Answers

It sounds like txtName is the server-side ID of your control. ASP.NET will use a different client-side ID when it renders the control as HTML: probably something like ctl00_Container_txtName.

You need to use the control's ClientID property to get the client-side ID, and then use that in your getElementById call:

var name = document.getElementById('<%=txtName.ClientID%>').value;
like image 108
LukeH Avatar answered Sep 19 '22 02:09

LukeH