1

I want to randomly select an id or value from one of the many option items in my select tag. Also I was wandering how do I quickly count all the option tags in my select tag, and how can I randomly call an ID field efficiently so if I hit refresh, it will just pick another random id? This is for a testing environment to auto fill a form out for qa people.

Examples

<select id="selectVendor">
 <option value="55" selected="selected">Company A</option>
 <option value="56">Company B</option>
 <option value="57">Company XYZCYK</option>
... </select>

Finally I want to put the value of my selected id into my form field... Eventually I want to use ajax to populate my entire form with the randomly selected identifier when the page first loads. thx

<input type="text" id="txtCompany" value="empty" />
RetroCoder
  • 2,597
  • 10
  • 52
  • 81
  • 1
    How about [Select random elements](http://stackoverflow.com/questions/1764160/jquery-select-random-elements) or [Getting random value from an array](http://stackoverflow.com/questions/4550505/javascript-getting-random-value-from-an-array) or the [MDN documentation of `Math.random`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Math/random)? – Felix Kling Sep 28 '11 at 00:25

4 Answers4

1
   $("#txtCompany").val(
       $("#selectVendor option").eq(
         Math.floor(Math.random() * $("#selectVendor option").length + 1)
         ).val()); 

Live example here: http://jsfiddle.net/rkMYB/1/

Community
  • 1
  • 1
imsky
  • 3,239
  • 17
  • 16
1
$('#selectVendor option').size();

Will give you the options number.

var randomOption=Math.floor(Math.random()*$('#selectVendor option').size());
$("#selectVendor option[value='"+randomOption+"']").attr('selected', 'selected');

Will select a random option.

Simon Arnold
  • 15,849
  • 7
  • 67
  • 85
  • randomOption is not distributed uniformly across all possible options in your example. Also, you're not rounding at all. Won't work. – Maximilian Hils Sep 28 '11 at 00:37
  • Sorry, i added the rounding, but I'm not sure I understand why you say *randomOption is not distributed uniformly across all possible options*, can you explain me, thx :) – Simon Arnold Sep 28 '11 at 00:49
1

Here's an easy to read jsfiddle to get you going. http://jsfiddle.net/z5aHm/15/

Takes the number of options there are, generates a random number between 0 and the number of options, and grabs the value of the option at that index.

Jake
  • 4,014
  • 8
  • 36
  • 54
1
var options = $("#selectVendor > option");

var random = Math.floor(options.length * (Math.random() % 1));

options.attr('selected',false)
.eq(random).attr('selected',true);

Sample at jsfiddle is here.

Maximilian Hils
  • 6,309
  • 3
  • 27
  • 46