Access a hidden field using jQuery

I have a page retrieved from the main page. On this page I have a hidden field ("hfUser"). How can I access this "hfUser" control and get / set its value using jQuery? I tried options for this:

$(document).ready(function() { var test = $("#hfUser").val(); alert(test); }); 

but test = undefined. I assume that I have the selector wrong, but I don’t know how to get asp hidden field. Any ideas?

thanks

+4
source share
4 answers

If you use Asp.net controls, the server will block the identifiers of the controls. It adds a bunch of management hierarchy information to the identifier. You need to indicate that this acutal id is to render, available with the ClientID property in the control (hfUser.ClientID) or access your control in a different, more workaround way, for example, search for the parent control and then search for its children, to find your control.

If you don't need to use the asp.net HiddenField control, try using plain old html input.

+6
source

ASP really loves to manipulate identifiers. The further down the rabbit hole (or nesting controls) you go, the more ASP adds your control identifier. Drop the master pages, and this is another level or two.

Another way to access server-side controls (with a set of runat properties) is to use square brackets in the jQuery selector.

Like this:

 $("[id$='hidImgSource']").val() 

This selects any elements whose identifier has "hidImgSource" as the trailing part of the name. That way, it will find malformed identifiers.

Here is a link to the jQuery Selectors page that explains some additional options.

+3
source

If the hidden field is an ASP.NET control, check out this blog post to help you with jQuery selectors for ASP.NET controls.

http://www.foliotek.com/devblog/extending-jquery-to-select-asp-controls/

+2
source

Do it like this:

 $(document).ready(function() { var test = $("**#<%= hfUser.ClientID %>**").val(); alert(test); }); 
0
source

All Articles