keyboardP
keyboardP

Reputation: 69392

Access hiddenfield using Jquery

I have a page that's derived from a master page. On this page, I have a hiddenfield ("hfUser"). How can I access this "hfUser" control and get/set its value using JQuery? I've tried variants of this:

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

});

but test = undefined. I'm guessing I've got the selector wrong, but I don't know how to get an asp hiddenfield. Any ideas?

Thanks

Upvotes: 4

Views: 20227

Answers (4)

Eric Burdo
Eric Burdo

Reputation: 814

ASP does like to mangle ID's. The further down the rabbit hole (or nesting controls) you go, the more ASP adds to your control ID. Throw in Master Pages, and it's yet another level or two.

Another way to access server-side controls (with the runat property set), is to use the square brackets in your jQuery selector.

Like this:

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

That selects any elements whose ID has 'hidImgSource' as ending part of the name. So it will find mangled ID's.

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

Upvotes: 3

Andreas
Andreas

Reputation: 26

Do it like this:

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

Upvotes: 0

Tim Banks
Tim Banks

Reputation: 7189

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/

Upvotes: 2

Doug R
Doug R

Reputation: 5779

If you are using Asp.net controls, the server will mangle the control ids. It adds a bunch of extraneous control tree hierarchy information into the id. You need to reference what that acutal id is that's getting rendered, which is availble with the ClientID property on the control (hfUser.ClientID) or access your control in a different, more roundabout way, like find the controls parent, then search through its children to find your control.

If you don't have to use the asp.net HiddenField control, try just using a regular old html input.

Upvotes: 6

Related Questions