Reputation: 4337
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
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
Upvotes: 1
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:
Upvotes: 3
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
Reputation: 173562
Probably the easiest is to use .map()
:
var types = $('#multiple > option:selected').map(function() {
return this.getAttribute('type');
}).get();
Upvotes: 2
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);
});
Upvotes: 3