简体   繁体   中英

jquery/javascript select option randomly

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 .

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/

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"

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);

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);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM