javascriptc#jqueryasp.netwebusercontrol

how to access usercontrol value in js/jquery


Suppose i created a user control which contain two textbox, one button

 --Start UserControl UserDetails--
 <asp:TextBox runat="server" id="txtName"></asp:TextBox>
 <asp:TextBox runat="server" id="txtAddress"></asp:TextBox>
--End UserControl UserDetails-

in aspx if i use the same user control,

<uc1:UserDetails runat="server" ID="UserDetails1" />
  1. how do i access the txtName using user control id UserDetails1?
  2. How do i make $('#UserDetails1').val() to return value of txtName?

Solution

  • Just add a public property for you TextBox in you user control code behind

    public TextBox Name
    {
        get { return txtName; }
        set { txtName = value; }
    }
    

    Now you can access your TextBox like this:

    <uc1:UserDetails runat="server" ID="UserDetails1" />
    
        <script>
            $(function () {
                $("#<%= UserDetails1.Name.ClientID%>").val("set you text here");
                //or
                var name = $("#<%= UserDetails1.Name.ClientID %>").val();
            });
        </script>