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 .

3
  • where is the question? where is your code? Commented Mar 6, 2012 at 4: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');` Commented Mar 6, 2012 at 4:10
  • how about looking at this first: stackoverflow.com/questions/7577047/… Commented Mar 6, 2012 at 4:14

4 Answers 4

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/

Sign up to request clarification or add additional context in comments.

Comments

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"

3 Comments

Did you try this? It doesn't seem to work for me in Chrome. It only works for me if I set xxx.selected = "selected".
@jfriend00 i changed .sel to sel :D
@jfriend00: Are you setting the attribute? The property should be boolean as shown.
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);

1 Comment

what if i want to select one of those options randomly except the first option? (usually empty option) – andufo just now edit
-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);
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.