Jason Jason - 1 year ago 104
jQuery Question

jQuery - getting custom attribute from selected option

Given the following:

<select id="location">
<option value="a" myTag="123">My option</option>
<option value="b" myTag="456">My other option</option>

<input type="hidden" id="setMyTag" />

$(function() {
var element = $(this);
var myTag = element.attr("myTag");


That does not work...

What do I need to do to get the value of the hidden field updated to the value of myTag when the select is changed. I'm assuming I need to do something about getting the currently selected value...?

Answer Source

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');
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download