Need a jQuery randomly selected identifier from options available
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" />
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.
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.
$('#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.
$("#txtCompany").val(
$("#selectVendor option").eq(
Math.floor(Math.random() * $("#selectVendor option").length + 1)
).val());
Live example here: http://jsfiddle.net/rkMYB/1/
精彩评论