jQuery - getting custom attribute from selected option

Jquery

Jquery Problem Overview


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

Jquery Solutions


Solution 1 - Jquery

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

Solution 2 - Jquery

Try this:

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

        $('#setMyTag').val(myTag); 
    }); 
}); 

Solution 3 - Jquery

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.

Solution 4 - Jquery

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.
});

Solution 5 - Jquery

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.

Solution 6 - Jquery

You're pretty close:

var myTag = $(':selected', element).attr("myTag");

Solution 7 - Jquery

The easiest one,

$('#location').find('option:selected').attr('myTag');

Solution 8 - Jquery

Simpler syntax if one form.

var option = $('option:selected').attr('mytag')

... if more than one form.

var option = $('select#myform option:selected').attr('mytag')

Solution 9 - Jquery

Here is the entire script with an AJAX call to target a single list within a page with multiple lists. None of the other stuff above worked for me until I used the "id" attribute even though my attribute name is "ItemKey". By using the debugger

Chrome Debug

I was able to see that the selected option had attributes: with a map to the JQuery "id" and the value.

<html>
<head>
<script type="text/JavaScript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
</head>
<body>
<select id="List1"></select>
<select id="List2">
<option id="40000">List item #1</option>
<option id="27888">List item #2</option>
</select>

<div></div>
</body>
<script type="text/JavaScript">
//get a reference to the select element
$select = $('#List1');

//request the JSON data and parse into the select element
$.ajax({
url: 'list.json',
dataType:'JSON',
success:function(data){

//clear the current content of the select
$select.html('');

//iterate over the data and append a select option
$.each(data.List, function(key, val){
$select.append('<option id="' + val.ItemKey + '">' + val.ItemText + '</option>');
})
},

error:function(){

//if there is an error append a 'none available' option
$select.html('<option id="-1">none available</option>');
}
});

$( "#List1" ).change(function () {
var optionSelected = $('#List1 option:selected').attr('id');
$( "div" ).text( optionSelected );
});
</script>
</html>

Here is the JSON File to create...

{  
"List":[  
{  
"Sort":1,
"parentID":0,
"ItemKey":100,
"ItemText":"ListItem-#1"
},
{  
"Sort":2,
"parentID":0,
"ItemKey":200,
"ItemText":"ListItem-#2"
},
{  
"Sort":3,
"parentID":0,
"ItemKey":300,
"ItemText":"ListItem-#3"
},
{  
"Sort":4,
"parentID":0,
"ItemKey":400,
"ItemText":"ListItem-#4"
}
]
}

Hope this helps, thank you all above for getting me this far.

Solution 10 - Jquery

$("body").on('change', '#location', function(e) {

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

});

Solution 11 - Jquery

Try This Example:

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

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

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

});

Solution 12 - Jquery

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>

Solution 13 - Jquery

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJasonView Question on Stackoverflow
Solution 1 - JquerySLaksView Answer on Stackoverflow
Solution 2 - JquerytvanfossonView Answer on Stackoverflow
Solution 3 - JqueryNawaManView Answer on Stackoverflow
Solution 4 - JquerypauloView Answer on Stackoverflow
Solution 5 - JqueryDavide GualanoView Answer on Stackoverflow
Solution 6 - JqueryCerinView Answer on Stackoverflow
Solution 7 - JqueryRobin HossainView Answer on Stackoverflow
Solution 8 - JqueryopenwonkView Answer on Stackoverflow
Solution 9 - JqueryCurtis FisherView Answer on Stackoverflow
Solution 10 - JqueryAmit-RlogicalView Answer on Stackoverflow
Solution 11 - JqueryDharmendra SinghView Answer on Stackoverflow
Solution 12 - JqueryAkhtar MunirView Answer on Stackoverflow
Solution 13 - JqueryinfomasudView Answer on Stackoverflow