Rhs
Rhs

Reputation: 3318

HiddenField.value is undefined in JS

In my aspx markup I have the following defined:

<asp:HiddenField runat="server" ClientIDMode="Static" ID="hidField" />

I have C# code as follows, which gives my hidden field a value:

hidField.value = check().ToString();

assume that check is a function which returns true, for simplicity.

I made JS code to do the following:

_myBool = $("#hidField");
alert(_myBool.value);

This alerts undefined.

For debugging purposes, I stepped through and saw that in C#, hidField.value is indeed true. And I tried alerting _myBool.length which returned 1 and _myBool which returned [Object object] so Im not calling undefined on undefined.

Upvotes: 1

Views: 8280

Answers (4)

MikeSmithDev
MikeSmithDev

Reputation: 15797

Make sure you are using the right ID:

_myBool = $("#<%= hidField.ClientID %>").val();

View your source when the page loads and check for that field. Chances are the ID is not "hidField". The code above will be correct.

Upvotes: 0

Ruben-J
Ruben-J

Reputation: 2693

You forgot the dollarsign and also use the val() function

alert($("#hidField").val());

Upvotes: 2

codingbiz
codingbiz

Reputation: 26376

Try this

_myBool = $("#hidField");  //my bool is a jQuery Object
alert(_myBool.val());   //can only get value with .val()

OR

_myBool = $("#hidField")[0];  //[0] gets the element in the object
alert(_myBool.value);  //can use the javascript .value

Upvotes: 2

Sushanth --
Sushanth --

Reputation: 55740

Missing $ symbol..

var  _myBool = $("#hidField");

alert(_myBool[0].value); // DOM Object 

alert(_myBool.val() );  // jQuery Object 

Also note the selector might Not work with runat="server" attribute as it prepends the content placeholder..

This is a better selector

 var _myBool = $('[id*="hidField"]');

Upvotes: 2

Related Questions