GCW
GCW

Reputation: 312

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.

Upvotes: 1

Views: 50

Answers (1)

Ram
Ram

Reputation: 144659

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);
});

Upvotes: 1

Related Questions