RagHaven
RagHaven

Reputation: 4337

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?

Upvotes: 2

Views: 10153

Answers (5)

hex494D49
hex494D49

Reputation: 9235

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

Upvotes: 1

imbondbaby
imbondbaby

Reputation: 6411

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.net/LFMG7/2/

Upvotes: 3

primehalo
primehalo

Reputation: 869

Perhaps something like this:

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

Upvotes: 0

Ja͢ck
Ja͢ck

Reputation: 173562

Probably the easiest is to use .map():

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

Demo

Upvotes: 2

Wilfredo P
Wilfredo P

Reputation: 4076

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

Upvotes: 3

Related Questions