Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery add additional data to new Option

Tags:

jquery

I would like to know if there is a possibility to add an additional data to a JQuery new Option. I got some select object and I append dynamically content:

select.append(new Option(item.name, item.id))

which produces a HTML for example like:

<option value="22">Uniqa OC Zawodu</option>

I want to add additional data to option, so my HTML would look like:

<option value="22" data-url="some_data">Uniqa OC Zawodu</option>
like image 532
Dawid Avatar asked Sep 26 '13 11:09

Dawid


1 Answers

What you have is vanilla JavaScript, you are not using jQuery library. Using jQuery you can pass an object to it. The properties of the object are mapped to their corresponding DOM properties. Note that data-* properties are cached by jQuery internally, and they are not added as attributes to the DOM, so they are not visible:

$('<option/>', {
    text: 'Uniqa OC Zawodu',
    value: 22,
    data: {
      url: 'some_data',
      whatever: 1 
    }
}).appendTo(select);

For retrieving the data-* properties you can use .data() method:

var url = $('option').data('url');
like image 94
undefined Avatar answered Sep 21 '22 14:09

undefined