简体   繁体   中英

how to get data from html5 data attribute, which is in a select list, into an array?

I have to basically 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.

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

I dont have to upload data as hidden select list, if you have a better advice pl let me know.

$.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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM