Adding Additional Data to Select Options Using Jquery

Adding additional data to select options using jQuery

HTML Markup

<select id="select">
<option value="1" data-foo="dogs">this</option>
<option value="2" data-foo="cats">that</option>
<option value="3" data-foo="gerbils">other</option>
</select>

Code

// JavaScript using jQuery
$(function(){
$('select').change(function(){
var selected = $(this).find('option:selected');
var extra = selected.data('foo');
...
});
});

// Plain old JavaScript
var sel = document.getElementById('select');
var selected = sel.options[sel.selectedIndex];
var extra = selected.getAttribute('data-foo');

See this as a working sample using jQuery here: http://jsfiddle.net/GsdCj/1/

See this as a working sample using plain JavaScript here: http://jsfiddle.net/GsdCj/2/

By using data attributes from HTML5 you can add extra data to elements in a syntactically-valid manner that is also easily accessible from jQuery.

JQuery add additional data to new Option

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');

Append option in select and add data attribute to option

There are some mistakes in your code. First of all, to set multiple attributes, you need to pass them as an object. Second, the property name and value for the data attributes are incorrect. brand & model should be property and abc & 123 should be their values respectively.

new Option will create an option element which does not have attr method on it. You may use jQuery to create a new element.

Here's the correct way

$('select[name="slc_pc"]')
.append($('<option />') // Create new <option> element
.val('Hello') // Set value as "Hello"
.text('Hello') // Set textContent as "Hello"
.prop('selected', true) // Mark it selected
.data({ // Set multiple data-* attributes
brand: 'abc',
model: '123'
})
);

Adding options to a <select> using jQuery?

This did NOT work in IE8 (yet did in FF):

$("#selectList").append(new Option("option text", "value"));

This DID work:

var o = new Option("option text", "value");
/// jquerify the DOM object 'o' so we can use the html method
$(o).html("option text");
$("#selectList").append(o);

Populate select options using jQuery and data attribute values

You can take the <li>s' texts and create <option>s for each of them.

Something like:

$('#onderwijs').on('shown.bs.modal', function() {  const dates = $('#course1 li').map((i, li) => $(li).text()).get();  // dates = ['2020-12-05', '2019-09-05', '2028-05-04']  let html = dates.map(date => {    return `<option>${date}</option>`;  }).join('');  // html = <option>2020-12-05</option><option>2019-09-05</option><option>2028-05-04</option>    $('#dates').html(html);});
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"><script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"></script><script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
<a class="programma-kiezer" data-prog="Forming Fase" href="#" data-toggle="modal" data-target="#onderwijs">button</a>
<ul id="course1"> <li>2020-12-05</li> <li>2019-09-05</li> <li>2028-05-04</li></ul>
<div class="modal" id="onderwijs" tabindex="-1" role="dialog"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title">Modal title</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">×</span> </button> </div> <div class="modal-body"> <form> <select id="dates"></select> </form> </div> <div class="modal-footer"> <button type="button" class="btn btn-primary">Save changes</button> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> </div> </div> </div></div>

What is the best way to add options to a select from a JavaScript object with jQuery?

The same as other answers, in a jQuery fashion:

$.each(selectValues, function(key, value) {   
$('#mySelect')
.append($("<option></option>")
.attr("value", key)
.text(value));
});

jquery - add extra data inside select tag

Use jQuery's attr() method to add(or update) attribute to element:

Add new attribute with:

$("#state-au").attr("eform","Australian State::1");

Remove attribute with:

$("#state-au").removeAttr("eform");

Solution:

$('#country').bind('change', function (e) {
if( $('#country').val() == 'AU') {
$("#state-au").attr("eform","Australian State::1");
$('#stateAU').slideToggle('fast');
}
else {
$("#state-au").removeAttr("eform");
$('#stateAU').hide();
}
}).trigger('change');

I would recommend use .data() if you want to bind data to a specific element. Check the following example.

Set data use: $("#state-au").data("eform", "Australian State::1")

Get data use: $("#state-au").data("eform")

Remove data use: $("#state-au").removeData("eform")

.data()

Store arbitrary data associated with the matched elements or return the value at the named data store for the first element in the set of matched elements.

REF: https://api.jquery.com/data/

The .data() method allows us to attach data of any type to DOM elements in a way that is safe from circular references and therefore from memory leaks.

.removeData()

The .removeData() method allows us to remove values that were previously set using .data(). When called with the name of a key, .removeData() deletes that particular value. When called with no arguments, .removeData() removes all values.

REF: https://api.jquery.com/removeData/