Note, if you're looking to retrieve the option that was selected when the page loaded (not the currently selected option) you can use $('option[selected]', this) instead (note: if no option was selected when the page loaded, that will return no matches, so calling attr() on that will result in undefined.
To retrieve a data-* attribute value as an unconverted string, use the attr() method. Since jQuery 1.6, dashes in data-* attribute names have been processed in alignment with the HTML dataset API. $( "div" ).
Retrieving a custom attribute is a simple process. First, declare an instance of the attribute you want to retrieve. Then, use the Attribute. GetCustomAttribute method to initialize the new attribute to the value of the attribute you want to retrieve.
$("#mySelect option:selected"). each(function () { $(this). removeAttr('selected'); });
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');
Try this:
$(function() {
$("#location").change(function(){
var element = $(this).find('option:selected');
var myTag = element.attr("myTag");
$('#setMyTag').val(myTag);
});
});
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:
$("#location").change(function(){
var element = $("option:selected", this);
var myTag = element.attr("myTag");
$('#setMyTag').val(myTag);
});
In the callback function for change()
, this
refers to the select, not to the selected option.
You're pretty close:
var myTag = $(':selected', element).attr("myTag");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With