2

I want to select an option from select randomly.

<select class=".sel" id="sel">
    <option>a</option>
    <option>b</option>
    <option>c</option>
    <option>d</option>
</select>

actually i am using jQuery autocomplete.

Well,the question is how can i select option randomly from a select box ?

and what i tried is

function change_something(opt)
    {
    var randomOption=Math.floor(Math.random()*$(opt+' option').size());
    $(opt+ option["value='"+randomOption+"'"]).attr('selected', 'selected');
  }

Actually i am not a jQuery expert,so i am getting failed to change something .

Red
  • 6,230
  • 12
  • 65
  • 112
  • where is the question? where is your code? – charlietfl Mar 06 '12 at 04:10
  • @elclanrs Thank ou for the contribution to the question,i tried something ` var randomOption=Math.floor(Math.random()*$(opt+' option').size()); $(opt+ option["value='"+randomOption+"'"]).attr('selected', 'selected');` – Red Mar 06 '12 at 04:10
  • how about looking at this first: http://stackoverflow.com/questions/7577047/need-a-jquery-randomly-selected-identifier-from-options-available – Sudhir Bastakoti Mar 06 '12 at 04:14

4 Answers4

11

Something like this should work:

var $options = $('#sel').find('option'),
    random = ~~(Math.random() * $options.length);

$options.eq(random).prop('selected', true);

http://jsfiddle.net/elclanrs/8DPMN/

elclanrs
  • 92,861
  • 21
  • 134
  • 171
6

That's what you need

options = $("#sel > option")
options[Math.floor(Math.random() * options.length)].selected = true

Also, use class="sel" instead of class=".sel"

Daniil Ryzhkov
  • 7,416
  • 2
  • 41
  • 58
3

This will work with your HTML example snippet.

var options = $("#sel > option");

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

$("#sel > option").attr('selected',false).eq(random).attr('selected',true);
Ryan Kempt
  • 4,200
  • 6
  • 30
  • 41
  • what if i want to select one of those options randomly except the first option? (usually empty option) – andufo just now edit – Andres SK Apr 09 '16 at 03:01
-1

Change your class from ".sel" to "sel", then Try:


$(document).ready(function() {
   var index = Math.floor(Math.random() * $(".sel option").length) + 1;
  $("select option:nth-child(" + index + ")").prop("selected", true);
});

Sudhir Bastakoti
  • 99,167
  • 15
  • 158
  • 162