-2

Can someone help provide the jQuery to be able to randomly select an option from an existing select object?
For example:

<select id="items">
    <option value="1">Item A</option>
    <option value="4">Item B/option>
    <option value="8">Item C</option>
</select>

Since the values are not sequential, I assume I can't use the $('#items option').length as a multiplier for Math.random.

timss
  • 9,982
  • 4
  • 34
  • 56
PaulMc
  • 3
  • 4
  • Yes you can, you're selecting an `option` element, *not* a given `value`. The `value` and option-index are *not* the same thing. – David Thomas May 16 '13 at 21:58
  • Sure you can. Indexing into that array doesn't depend on what the values of the options are. – Barmar May 16 '13 at 21:59

2 Answers2

2
var options = $('#items option'),
    min     = 0,
    max     = options.length,
    rand    = Math.floor(Math.random() * (max - min + 1)) + min;

var random_option_value = options.eq( rand ).text();

// to set the select to a random option, do :
// $('#item').val( options.eq( rand ).val() );

Make sure you close the middle option

adeneo
  • 312,895
  • 29
  • 395
  • 388
0

Try this:

var length = $('#items option').length;
var pick = Math.floor(Math.random()*length);
var randomOption = $('#items option')[pick];
ericbowden
  • 2,177
  • 1
  • 19
  • 21