AndroidDev93 AndroidDev93 - 3 years ago 124
Javascript Question

getting attribute values from selected options in multiselect

I have a multi select element in jQuery.

Here is an example.

<select multiple id="multiple">
<option value="1" type="Alice">Option 1</option>
<option value="2" type="Bob">Option 2</option>
</select>


I know I can get all the values that are selected by doing
$("#multiple").val();


How can I also get the type attributes of the selected options?

Answer Source

You need uses a pseudo option:selected and look every option selected:

$('#multiple').change(function(){
    var $value =$('option:selected',this).attr('type');
    console.log($value);
});

Or using the .each() like:

$('#multiple option:selected').each(function(){
    var $value =$(this).attr('type');
    console.log($value);
});

DEMO

DEMO With .each()

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download