admin管理员组

文章数量:1279008

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?

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?

Share Improve this question edited Jul 26, 2017 at 8:28 Suneel Kumar 1,6642 gold badges21 silver badges31 bronze badges asked Jun 25, 2014 at 1:20 RagHavenRagHaven 4,34725 gold badges75 silver badges114 bronze badges 1
  • With HTML5 you can use .selectedOptions; it's a collection of Option elements from which you can get the attribute values. – Ja͢ck Commented Jun 25, 2014 at 1:40
Add a ment  | 

5 Answers 5

Reset to default 3

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

Try this:

$(document).on("change", "#multiple", function(){
    var ids = $(this).find('option:selected').map(function() {
        return $(this).attr('type');    
    }).get();
    console.log(ids);
});

JSFiddle:

http://jsfiddle/LFMG7/2/

Probably the easiest is to use .map():

var types = $('#multiple > option:selected').map(function() {
    return this.getAttribute('type');
}).get();

Demo

var t = document.getElementById('multiple'), a = [], i;
for(i = 0; i < t.length; i++) {
    if(t[i].selected) a.push(t[i].getAttribute('type'));
}
// tested on IE8+, Chrome (Windows & Linux), Safari, Firefox (Windows & Linux), Opera 

Fiddle

Perhaps something like this:

var myList = array();
$('#multiple option:selected').each(function(){
    myList.push({"val":$(this).val(), "type":$(this).attr("type")});
});

本文标签: javascriptgetting attribute values from selected options in multiselectStack Overflow