Reputation: 643
I have a select multiple with some options. Each option has multiple data- attributes. I would like to create an array that contains each of its data- values. For example my code looks a lot like this:
<select multiple id='my_select'>
<option data-my_id='1' data-my_parent='3' data-my_name='option1'>My first option</option>
<option data-my_id='2' data-my_parent='3' data-my_name='option2'>My second option</option>
<option data-my_id='3' data-my_parent='3' data-my_name='option3'>My third option</option>
</select>
And the result I am looking for needs to be something like this:
[1,3,option1], [2,3,option2], [3,3,option3]
I have researched how to create an array with one of the data- attribute value for each of the options, giving me this [1,2,3], but I have been unsuccessful in coming up with what I need.
Thanks a lot!
Upvotes: 12
Views: 16882
Reputation: 145478
var array = $("#my_select > option").map(function() {
return [$.map($(this).data(), function(v) {
return v;
})];
}).get();
DEMO: http://jsfiddle.net/nQ6mE/
Upvotes: 20
Reputation: 94141
var arr = [];
$('#my_select option').each(function(){
var $this = $(this);
arr.push([ $this.data('my_id'), $this.data('my_parent'), $this.data('my_name') ]);
});
Upvotes: 8