WpDoe WpDoe - 7 months ago 8
HTML Question

What HTML element to use for holding hidden values

In my application I have a need to keep some values hidden, for them to be later picked up by jQuery.

I have a following div for keeping map's data (after

img
is clicked I would like to show a map with 2 markers):

<div class="map-data">
<img src="../map.png">
</div>


In order to do that I need to store 4 hidden values (
1_lat, 1_long, 2_lat, 2_long
), like:

<label type="hidden" value="56.056180">


What would the right hidden element be for storing such values?
Label
,
p
or something else?

Answer

Since it seems that you will only use those values client-side, i.e. you are not going to send them back to the server, it seems wrong to me to use an input element.

The comments already have two very good advice, here expanded.


Personally I would use data attributes if I needed per-element data (data that varies per element).

<div id="sampleMap" data-lat1="0.241" data-lat2="0.56">
   ...
</div>

<div id="anotherSampleMap" data-lat1="0.87" data-lat2="0.283">
   ...
</div>

They can be accessed very easily.

function configureTheMap(map)
{
    var lat1 = map.dataset.lat1;
    var lat2 = map.dataset.lat2; 

    ...
}

...

configureTheMap(document.getElementById('sampleMap'));
configureTheMap(document.getElementById('anotherSampleMap'));

You should check browser compatibility though.

If the data was global I would simply generate a JavaScript object

var coordinates_config = {lat1 : 0.241, lat2 : 0.56};

and use it accordingly

function configureTheMap(map)
{
    var lat1 = coordinates_config.lat1;
    var lat2 = coordinates_config.lat2; 

    ...
}

You can generalize this method easily to be used for per-element data if data attributes are not supported by the browsers you are targeting.

In both cases, allow me to remember the importance of proper escaping when generating the markup/code.