jQuery - getting custom attribute from selected option

Viewed 390357

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

14 Answers

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.

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");

The easiest one,

$('#location').find('option:selected').attr('myTag');
$("body").on('change', '#location', function(e) {

 var option = $('option:selected', this).attr('myTag');

});

Try This Example:

$("#location").change(function(){

    var tag = $("option[value="+$(this).val()+"]", this).attr('mytag');

    $('#setMyTag').val(tag); 

});

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>

Stright forward way is :

Get selected option attribute value:

var selectedOptionAttributeValue =   $('#location option:selected').attr('myTag');

Get Selected Text:

 var selectedOptionText = $('#location').text();

Get selected value:

var selectedOptionValue = $('#location').val();
var optionAttr1 = $(this).find('option:selected').attr("myTag");
var optionAttr = $('#location option:selected').attr("myTag");
Related