3

I have a simple JQuery code where I'm trying to get the value of an ASP:HiddenField and display it, but it does not show anything.

The hidden field is in the form, not inside any table or div.

<asp:HiddenField ID="hdnID" runat="server" />
$(document).ready(function () {
    $("#btnload").click(function () {
        alert($("#hdnID").text());
    });
});

I am setting the value of hidden field on page load and then when I click the button I want to display the value using alert. It shows an empty alert box every time.

What am I doing wrong?

David H.
  • 953
  • 1
  • 8
  • 20
S. Arzoo
  • 73
  • 1
  • 1
  • 6

2 Answers2

6

Try this instead alert($("#hdnID").val());

David H.
  • 953
  • 1
  • 8
  • 20
  • Well, I feel so stupid now. I was trying to do this with a label first, and when I changed to the hidden field I didn't think of changing text to val. Thank you so much. – S. Arzoo Feb 17 '16 at 15:56
3

If anyone tries the above and it is still not working:

If your hidden is nested in other controls, ASP.NET will change the name of the control, so better to select for "name ends with" selector id$

eg: alert($('[id$="hdnID"]').val());

Alternatively have ASP.NET populate the name of the control with:

alert($('#<%= hdnID.ClientID%>').val());

Either will insure reference to your hidden field if it is nested.

mike
  • 2,149
  • 20
  • 29