7

I have two hidden input fields in my form:

<input type="hidden" name="lat" id="lat" value=""/>
<input type="hidden" name="long" id="long" value="" />

I am assigning their value by doing the following:

document.getElementById('lat').value = lat;
document.getElementById('long').value = lng;

Can someone please tell me how I can remove the hidden <input> fields and replace them with a @Html.HiddenFor<> and make my Javascript update the HiddenFor? I want to do this because it will obviously automatically bind the data.

My HiddenFor currently looks something like this:

@Html.HiddenFor(m => Model.Listing.Location.Latitude);
@Html.HiddenFor(m => Model.Listing.Location.Longitude);

I change the Javascript to do this:

document.getElementById('Listing.Location.Latitude').value = lat;
document.getElementById('Listing.Location.Longitude').value = lng;

I get the following error in the Console:

Uncaught TypeError: Cannot set property 'value' of null 

Can anyone see where I am going horribly wrong?

dove
  • 20,469
  • 14
  • 82
  • 108
Subby
  • 5,370
  • 15
  • 70
  • 125

3 Answers3

11

The Ids of these fields will have underscores not dots, their names will have the dots. Try this:

document.getElementById('Listing_Location_Latitude').value = lat;
dove
  • 20,469
  • 14
  • 82
  • 108
5

Try this.

@Html.HiddenFor(m => m.Listing.Location.Latitude, new {id = "theIdyouWant"})

So you can get the element using Javascript:

document.getElementById("theIdyouWant")
John Hpa
  • 463
  • 6
  • 18
3

Your problem is that id will be another. Listing.Location.Latitude is name attribute.

For example:

@Html.TextBoxFor(x => x.General.Site_Name)

generated as:

<input id="General_Site_Name" type="text" name="General.Site_Name" />
webdeveloper
  • 17,174
  • 3
  • 48
  • 47