Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery: Create an array made out of the data- attributes of my select options

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!

like image 937
murielg Avatar asked Dec 21 '12 22:12

murielg


People also ask

How do I create an array in jQuery?

Syntax And Declaration:var arr1=[]; var arr2=[1,2,3]; var arr2=["India","usa","uk"]; Type of Array: The type of an array is “object“. Iteration Approach: We use the length property of the array to iterate in the array.

How get data attribute value in jQuery?

To retrieve a data-* attribute value as an unconverted string, use the attr() method. Since jQuery 1.6, dashes in data-* attribute names have been processed in alignment with the HTML dataset API. $( "div" ).

How add data attribute in jQuery?

Alternatively, you can also use the jQuery data() method (jQuery version >= 1.4. 3), to get the data-attribute of an element using the syntax like $(element). data(key) . That means in the above example to get the data-id using data() method you can use the statement like $(this).

How do I select an element by a data attribute?

Use the querySelector method to get an element by data attribute, e.g. document. querySelector('[data-id="box1"]') . The querySelector method returns the first element that matches the provided selector or null if no element matches the selector in the document.


1 Answers

var array = $("#my_select > option").map(function() {
    return [$.map($(this).data(), function(v) {
        return v;
    })];
}).get();

DEMO: http://jsfiddle.net/nQ6mE/

like image 181
VisioN Avatar answered Oct 22 '22 23:10

VisioN