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!
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.
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" ).
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).
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.
var array = $("#my_select > option").map(function() {
return [$.map($(this).data(), function(v) {
return v;
})];
}).get();
DEMO: http://jsfiddle.net/nQ6mE/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With