jquery/javascript select option randomly

倾然丶 夕夏残阳落幕 提交于 2020-01-03 04:52:08

问题


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 .


回答1:


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/




回答2:


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:


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



回答4:


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



来源:https://stackoverflow.com/questions/9577747/jquery-javascript-select-option-randomly

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!