Javascript jQuery选择随机数量的复选框不起作用

Javascript jQuery选择随机数量的复选框不起作用,javascript,jquery,Javascript,Jquery,我用最小标记进行的简单测试效果不错,但想想主站点生成的标记会阻止它工作,因为它会选择所有10个选项,而不是随机选择6个选项。有人有什么想法吗 $(“.random pick”)。单击(函数(){ var maxAllowed=6; //计数复选框 var random_checkbox=$(“#content_subscribtion_uinput.checkbox”).size(); //选中随机复选框,直到达到“maxAllowed”限制 while($(“#content_subscri

我用最小标记进行的简单测试效果不错,但想想主站点生成的标记会阻止它工作,因为它会选择所有10个选项,而不是随机选择6个选项。有人有什么想法吗

$(“.random pick”)。单击(函数(){
var maxAllowed=6;
//计数复选框
var random_checkbox=$(“#content_subscribtion_uinput.checkbox”).size();
//选中随机复选框,直到达到“maxAllowed”限制
while($(“#content_subscribtion_input.checkbox:checked”).size()



为您的方框选择项目 您已从6个选项中选择了0个

注意:如果您愿意,您可以每月更改/交换方框内容

不能决定?让我们帮助,随机选择框项目

食物-种植青葱:红日: 食物-种植青葱:黄金美食 : 食物-种植茄子、甜椒: 食物-种植草药:罗勒、欧芹: 食物-种植香草:芫荽、蒜葱: 花-尼琳·鲍德尼·伊莎贝尔 : 花卉-尼琳·鲍德尼·阿尔巴: 花卉-尼琳·鲍德尼·尼基塔: 唐菖蒲 : 混合花秋海棠 : 可利用性: 有现货的 数量: + − 订购这个箱子
您必须将所有复选框存储到一个数组中,每次从该数组中选择一个随机复选框,将其从数组中删除并选中,如下所示:

$(".random-pick").click(function() {
  var maxAllowed = 6;

  // map the checkboxes into an array
  var checkboxes = $("#content_subscribtion_ input.checkbox").map(function() {
    return this;
  });

  // uncheck all the checkboxes
  $(checkboxes).prop("checked", false);

  /* OPTIMIZATION GOES HERE (see note bellow) */

  // repeat this maxAllowed times
  while(maxAllowed--) {
    // get a random index from the array of checkboxes
    var rand = Math.floor(Math.random() * checkboxes.length);
    // get the checkbox at that index (splice will remove it from the array as well so we won't have the chance to get the same checkbox multiple times) (splice return an array so we have to use [])
    var checkbox = checkboxes.splice(rand, 1)[0];
    // check that checkbox we just got
    $(checkbox).prop("checked", true);
  }
});
示例:

$(“.random pick”)。单击(函数(){
var maxAllowed=6;
var复选框=$(“#内容u订阅uu输入.checkbox”).map(函数(){
归还这个;
});
$(复选框).prop(“选中”,false);
while(maxAllowed--){
var rand=Math.floor(Math.random()*复选框.length);
var复选框=复选框。拼接(rand,1)[0];
$(复选框).prop(“选中”,true);
}
});



为您的方框选择项目 您已从6个选项中选择了0个

注意:如果您愿意,您可以每月更改/交换方框内容

不能决定?让我们帮助,随机选择框项目

食物-种植青葱:红日: 食物-种植青葱:黄金美食 : 食物-种植茄子、甜椒: 食物-种植草药:罗勒、欧芹: