Get attribute from select option different from value

29 Views Asked by At

After a ajax call i populate a select option in this way adding a value attribute and another one called jobDescription:

$.each(obj, function(key, value) {   
                 $('#mySelect').append($("<option></option>").attr({"value": value.id, "jobDescription": value.jobDescription}).text(value.name)); 
            });

when i select one of the option i need to get the jobDescription value. To do that I tried in this way

$("#mySelect").on('change', function() {
   console.log($(this).attr("jobDescription"));
});

but it returns undefined. Is there any other way to do that?

1

There are 1 best solutions below

0
Carl Binalla On

Going by your original code, you need to first add find(':selected'). first before the .attr to find the current selected <option> in #mySelect.

$(function() {
  $("#mySelect").on('change', function() {
    console.log($(this).find(':selected').attr("jobDescription"));
  });

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="mySelect">
  <option value="someValue" jobDescription="jobDesc1">Lorem Ipsum 1</option>
  <option value="someValue" jobDescription="jobDesc2">Lorem Ipsum 2</option>
  <option value="someValue" jobDescription="jobDesc3">Lorem Ipsum 3</option>
</select>