最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

jqueryjavascript select option randomly - Stack Overflow

programmeradmin2浏览0评论

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 .

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 .

Share Improve this question edited Mar 6, 2012 at 4:12 Red asked Mar 6, 2012 at 4:06 RedRed 6,38813 gold badges66 silver badges113 bronze badges 3
  • where is the question? where is your code? – charlietfl 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');` – Red Commented Mar 6, 2012 at 4:10
  • how about looking at this first: stackoverflow.com/questions/7577047/… – Sudhir Bastakoti Commented Mar 6, 2012 at 4:14
Add a comment  | 

4 Answers 4

Reset to default 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/

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

发布评论

评论列表(0)

  1. 暂无评论