Search code examples
javascriptjquerycustom-data-attribute

How to get data from HTML data attributes into an array?


I have to upload some data with form load, to be used in JavaScript operations on the page. I am uploading the data like below:

<select id="allrecords">
    <option data-s-type="X" data-n-type="9" value="xxx">xxx</option>
    <option data-s-type="X" data-n-type="9" value="lmn">lmn</option>
    <option data-s-type="X" data-n-type="8" value="xyz">xyz</option>
    <option data-s-type="Y" data-n-type="3" value="zzz">zzz</option>
    ...
</select>

From this data, data-s-type and data-n-type properties are used in finding out which values will be added to an array, which is later being used in the program. I am not able to think of a way to get that array using this select list.

e.g. when data-s-type="X" AND data-n-type=9, array = [xxx,lmn]

I don't have to upload data as hidden select list.


Solution

  • $.map creates arrays, and inside the function you check for the values you'd like, and if they match you return the elements value to the array, like so:

    var arr = $.map($('#allrecords option'), function(el,i) {
        if ($(el).data('s-type') == 'X' && $(el).data('n-type') == '9') 
          return el.value;
    });
    
    arr //is now ['xxx', 'lmn']
    

    FIDDLE