Prasob
Prasob

Reputation: 2183

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?

Upvotes: 1

Views: 4136

Answers (4)

Appu
Appu

Reputation: 39

Copy the id of particular textbox from Developer Tools and then just use that id like below

var textLength = $("#ContentBody_ucMFA1_txtACode").val().length;

 function Disable() {
            var textLength = $("#ContentBody_ucMFA1_txtACode").val().length;
            if (textLength > 0) {
                if (Page_ClientValidate()) {
                    document.getElementById("divButtons").style.display = "none";
                }
            }
        }

Upvotes: 0

Ravinder Gujiri
Ravinder Gujiri

Reputation: 1514

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>

Upvotes: 3

Vishal Surjuse
Vishal Surjuse

Reputation: 170

Try this, using Jquery

$("[id$='txtName']").val();
$("[id$='txtAddress']").val(); 

Upvotes: 3

Anoop H.N
Anoop H.N

Reputation: 1264

Use data keys inside your text boxes.

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

<uc1:UserDetails runat="server" ID="UserDetails1" data-usercontrol = "UserDetails1" />

in jquery,

$("[data-usercontrol='UserDetails1']").find("[data-key='name']").val();
$("[data-usercontrol='UserDetails1']").find("[data-key='address']").val();

You can use id selector. But since you have used asp.net, it might be rendered with different id in HTML.

Hope this helps!

Upvotes: 0

Related Questions