I have a select element that I am adding options to dynamically using data from a variable called 'results':
HTML:
<select id="categories">
<option selected disabled>Select your category</option>
</select>
jQuery:
$.each(results.Subcategories, function(index,category) {
var category = '<option value="'+category.Name+'" data-index="'+index+'">'+category.Name+'</option>';
$('#categories').append(category);
});
This works correctly and I am able to choose between the dynamically added options in the select element.
What I need to do now is get the 'value' attribute of the currently selected AFTER the user has chosen it from the added options. This is where I am getting stuck. I thought that something like this would work:
$('#categories').on('change', function() {
var optionSelected = $("#categories option:selected", this);
console.log($(optionSelected).data("value"))
});
But the selected attribute does not move on the options when I choose a new one, so I am unable to target that attribute to get the value.
Assuming the approach above is solid, how do I get my newly selected option to have the selected attribute so I can target it and get the value? Or is there a better approach that I'm missing? Thanks in advance.