views:

1430

answers:

5

I have Hidden field like

<%= Html.Hidden("ID", 1) %>

and in javascript i want a value of that field by

var ID = document.getElementsByName("ID").value;

I can't access it!

is there any other way?

+3  A: 

Not sure of the context but shouldn't you be using getElementById ??

sbohan
Actually, since the post is tagged with ASP.NET MVC, he should be using jQuery (since it's included with the template). $('#ID') works nicely.
tvanfosson
Fair enough, didn't notice the tag! I was referring to the use of ByName instead of ById, which is what I thought was causing it to not work.
sbohan
+1  A: 

Perhaps what you want to be doing is:

var id = document.getElementById('id').value;
vezult
+3  A: 

Try this :

<input type="hidden" id="ID" />

for javascript to access it :

var ID = document.getElementById("ID").value;

other way with JQuery :

var ID = $('#ID').val();
Canavar
+1 for jQuery, -1 for Elements instead of Element
tvanfosson
yes, I copied from original question, forget it :)
Canavar
I've corrected the typo. So now you only get the +1.
tvanfosson
I especially like this answer for including jQuery because the question was tagged with MVC. Someone using MVC really ought to be using jQuery.
tvanfosson
+1  A: 

id do this:

<% Html.Hidden("ID", 1, new { id = "MyHidden"}) %>

document.getElementById("MyHidden").value
Andrew Bullock
A: 
  1. getElementsByName(name) returns an array of elements with the given name property.
  2. getElementById(id) returns the element with the given id property.
  3. There is no getElementsById - because two elements with same id is not allowed.
  4. Nor are getElementsByID, getElementByID - these aren't existing javascript functions. Camelization is required!

Answering the question:

You can get the id of a hidden element if it is hidden client side. (You can see it in the generated source.)

document.getElementById('ID').value;

Or something like this.

Vili