KodeFor.Me
KodeFor.Me

Reputation: 13511

HTML Option element with data attributes. Is it posible and if so, how to retrive value with jQuery?

I just wonder if is it posible to have option elements in html with data- attributes and so, if that posible how to retrive this value.

More specific. Lets say I have the following code:

<select name="areas" id="areas">
    <option value="1" data-lat="12.243" data-lng="32.43242">Area name</option>
    <option value="2" data-lat="14.243" data-lng="34.43242">Area name</option>
    <option value="3" data-lat="16.243" data-lng="36.43242">Area name</option>
    <option value="4" data-lat="18.243" data-lng="38.43242">Area name</option>
</select>

then, is it any way to get the data-lat and data-lng for from the selected option via jQuery ?

Upvotes: 8

Views: 14373

Answers (4)

Mohd Abdul Mujib
Mohd Abdul Mujib

Reputation: 13908

I'd like to add, If you want to target a specific <select>

You can also pass the container element so that <options> from only that element will be selected.

// For user with events like .on("change") etc.
console.log($("option:selected", this).attr("data-lat")); 

OR

console.log($("option:selected", "#areas").attr("data-lat"));

Upvotes: 2

Bernie
Bernie

Reputation: 5055

Yes that's possible. Any attribute value can be get by:

$('option:selected').attr('data-lng')

and set by:

$('option:selected').attr('data-lng', 1234);

Upvotes: 7

Oriol
Oriol

Reputation: 288000

Set attribute using setAttribute:

document.getElementById('areas')
    .getElementsByTagName('option')[index]
    .setAttribute('data-lng', 'foo');

Get attribute using getAttribute:

document.getElementById('areas')
    .getElementsByTagName('option')[index]
    .getAttribute('data-lng');

Both get and set:

var el = document.getElementById('areas')
    .getElementsByTagName('option')[index];
el.getAttribute('data-lng');
el.setAttribute('data-lng', 'foo');

Note 1 I have used document.getElementById('areas').getElementsByTagName('option')[index] because probably is more cross-browser, but you could use

  • document.getElementById('areas').getElementsByTagName('option')[index]
  • document.getElementById('areas').options[index]
  • document.getElementById('areas')[index]

Note 2 I have used setAttribute and getAttribute because they are more cross-browser, but you could also use dataset:

el.dataset.lng;            // get
el.dataset.lng = 'foo';    // set

Upvotes: 5

Musa
Musa

Reputation: 97672

You can use .data to retrieve data attributes from elements

$('#areas options').each(function(){
    console.log($(this).data('lat'), $(this).data('lng'));
}

The advantage of this over .attr is this is that you get type conversion so you'll get a Numeric value in this case rather than a string.

Upvotes: 2

Related Questions