jQuery - getting custom attribute from selected option
That because the element is the "Select" and not "Option" in which you have the custom tag.
Try this: $("#location option:selected").attr("myTag")
.
Hope this helps.
Suppose you have many selects. This can do it:
$('.selectClass').change(function(){
var optionSelected = $(this).find('option:selected').attr('optionAtribute');
alert(optionSelected);//this will show the value of the atribute of that option.
});
Try this:
$(function() {
$("#location").change(function(){
var element = $(this).find('option:selected');
var myTag = element.attr("myTag");
$('#setMyTag').val(myTag);
});
});
You're adding the event handler to the <select>
element.
Therefore, $(this)
will be the dropdown itself, not the selected <option>
.
You need to find the selected <option>
, like this:
var option = $('option:selected', this).attr('mytag');