How to get User Control value using Javascript in an .aspx file

Hello,

I have a aspx file that include a user control file. I need to get the textbox value that is in the user control page (user.ascx file) using javascript in the mypage.aspx file. Here is my code: 

mypage.aspx:

<%

@RegisterTagPrefix=”uc1″TagName=”user”Src=”user.ascx” %>

<

body>

<formid=”form1″runat=”server”>

<div>

<

uc1:userID=”user1″runat=”server”>uc1:user><br/><inputid=”btnSave” onclick=”return runit();” type=”button”value=”Save”name=”btnSave” runat=”server”> <br/>div> form>

body>

 

user.ascx file:

User ID:

<asp:TextBoxID=”userid”runat=”server”>asp:TextBox>

 

 The javascript in mypage.aspx is:

<

scriptlanguage=”javascript”>function runit()

{

var s = document.forms[0][‘user1:userid’].value;

alert(s);

}

script>

When I click on the save button, I always get the javascript error “document.forms.0.user1:userid.value’ is null or not  an object”. I did many research and found this is the only way to get user control value using javascript. Could someone please tell me if my code is wrong or there is other way to get it.

Thanks! 

 

 

 

 if the javascript  code is related to the usercontrol , place it inside the usercontrol instead of the page  , then use the ClientId like this    However  , if the javascript code  can’t be moved to UserControl , then you need ti expose the userid  TextBox clientId as a public property from your user  control , so inside the UserControl , you will need to write a public property which will return the ClientId of the TextBoxpublic string userIdClientId{get{return userid.ClientId;} }  Then you need to change the script to :    /

Thanx Anas for ur solution i think this should work with him

Thanks Anas! Your code  is very helpful and I can get the user  control value  by clicking on the save  button. However, there are 4 user control  files / pages in one aspx  page in my real project. The four user control pages will be displayed dynamically by setting true or false to the visible property. The Save button  is in mypage.aspx. If user.ascx page  is displayed currently and I click  the Save button, I can get the value, but if the user.ascx page is not displayed currently I will get “Object required” javascript  error. I know that is because the userid  textbox is not in mypage.aspx page when user.ascx is hidden. Do you know if there is a way to get the userid value using javascript? I need to check the value before submitting the page.Thanks again for your help!