Advertisement
Advertisement


jQuery - getting custom attribute from selected option


Question

Given the following:

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

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

<script>
    $(function() {
        $("#location").change(function(){
            var element = $(this);
            var myTag = element.attr("myTag");

            $('#setMyTag').val(myTag);
        });
    });
</script>

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...?

2010/02/09
1
225
2/9/2010 4:41:32 PM

Accepted Answer

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');
2010/02/09
528
2/9/2010 4:37:36 PM

Try this:

$(function() { 
    $("#location").change(function(){ 
        var element = $(this).find('option:selected'); 
        var myTag = element.attr("myTag"); 

        $('#setMyTag').val(myTag); 
    }); 
}); 
2010/02/09

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.

2010/02/09

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.

2010/02/09

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.
});
2011/11/13

You're pretty close:

var myTag = $(':selected', element).attr("myTag");
2010/02/09

Source: https://stackoverflow.com/questions/2230704
Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Email: [email protected]