简体   繁体   中英

Order random form options with javascript

I have some randomly generated form options I need to reorder, in a defined order.

Example:

<select id="the_size">
   <option value="">Select something</option>
   <option value="xl">XL</option>
   <option value="l">L</option>
   <option value="s">S</option>
</select>

Should be:

<option value="s">S</option>
<option value="l">L</option>
<option value="xl">XL</option>

And again:

<select id="the_size">
   <option value="">Select something</option>
   <option value="s">S</option>
   <option value="m">M</option>
   <option value="xs">XS</option>
</select>

Should be: xs, s, m.

How can I achieve this? Maybe hide everything, define an array (xs, s, m, l, xl, xxl..), loop a conditional statement and write every correspondent value if it exists.

You can sort the options and then (re)append them to the select element:

var c = ['xs', 's', 'm', 'l', 'xl', 'xxl'],
    s = document.querySelector('#the_size'), 
    o = [].slice.call(s.options);

o.sort(function(a, b) {
  return c.indexOf(a.value) - c.indexOf(b.value);
}).forEach(function(el) {
   s.appendChild(el);
});

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