6

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?

2 Answers 2

8

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;
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! How would one check if a check box is selected or not?
I suppose you'd just use the .checked property (a boolean) instead of the .value property.
0

You'd better use the Jquery.then,juest call:

$('<%=txtName.ClientID%>').value;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.