Given the following:
$("body").on('change', '#location', function(e) {
var option = $('option:selected', this).attr('myTag');
});
Simpler syntax if one form.
var option = $('option:selected').attr('mytag')
... if more than one form.
var option = $('select#myform option:selected').attr('mytag')
You can also try this one as well with data-myTag
<select id="location">
<option value="a" data-myTag="123">My option</option>
<option value="b" data-myTag="456">My other option</option>
</select>
<input type="hidden" id="setMyTag" />
<script>
$(function() {
$("#location").change(function(){
var myTag = $('option:selected', this).data("myTag");
$('#setMyTag').val(myTag);
});
});
</script>
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.
The easiest one,
$('#location').find('option:selected').attr('myTag');
You're pretty close:
var myTag = $(':selected', element).attr("myTag");