How to create a randomly select button 3 of 5 numbers

2

My question is, how to create a button that randomly and automatically selects 3 of the 5 numbers that are shown. Like I clicked on them.

Follow all my code below.

<html>
<head>
<style type="text/css">
input[type=checkbox] {
  display:none;
}
input[type=checkbox] + label {
  color: black;
  border: 1px solid #000;
  padding-left: 10px;
  padding-right: 10px;
  padding-top: 5px;
  padding-bottom: 5px;
}

input#input_1_1:checked + label {
  color: white;
  background-color:#4682B4;
  font-weight: 500;
  border: 1px solid #000;
}

input#input_1_2:checked + label {
  color: white;
  background-color:#4682B4;
  font-weight: 500;
  border: 1px solid #000;
}

input#input_1_3:checked + label {
  color: white;
  background-color:#4682B4;
  font-weight: 500;
  border: 1px solid #000;
}
input#input_1_4:checked + label {
  color: white;
  background-color:#4682B4;
  font-weight: 500;
  border: 1px solid #000;
}
input#input_1_5:checked + label {
  color: white;
  background-color:#4682B4;
  font-weight: 500;
  border: 1px solid #000;
}

</style>
</head>
<body>
<input type="text" id="resultado">
<input type='checkbox' name='q1_myOptions[]' onclick="add(this)" value="01" id="input_1_1"/>
<label for="input_1_1">01</label>
<input type='checkbox' name='q1_myOptions[]' onclick="add(this)" value="02" id="input_1_2"/>
<label for="input_1_2">02</label>
<input type='checkbox' name='q1_myOptions[]' onclick="add(this)" value="03" id="input_1_3"/>
<label for="input_1_3">03</label>
<input type='checkbox' name='q1_myOptions[]' onclick="add(this)" value="04" id="input_1_4"/>
<label for="input_1_4">04</label>
<input type='checkbox' name='q1_myOptions[]' onclick="add(this)" value="05" id="input_1_5"/>
<label for="input_1_5">05</label>


<script>
function add(_this){
  var resultado = document.getElementById('resultado');
  var value = _this.value;
  var hasAdd = resultado.value.search(_this.value) > 0
  if(_this.checked && !hasAdd){
    resultado.value += ' '+_this.value;
  }else if(!_this.checked && hasAdd){
    var er = new RegExp(_this.value, 'ig');
    resultado.value = resultado.value.replace(er, '');
  }
  resultado.value = resultado.value.replace(/ {2,}/g, ' ');
}
</script>

</body>
</html>
    
asked by anonymous 11.10.2017 / 13:18

4 answers

2

I suggest that you build an array with elements that are inputs of type checkbox . Then loop the amount of elements you want to sort and mark each element drawn and removed from the array so you can not go out again.

Example:

function sortearElementos(quantidade){

  const checkboxes = [...document.querySelectorAll("input[type=checkbox]")]; 
  checkboxes.forEach(c => c.checked=false); //desmarcar todas as checkboxes primeiro

  for (let i = 0; i < quantidade; ++i){
    //gerar o aleatorio com random() e escalando ao tamanho do array
    let sorteado = Math.floor(Math.random()*checkboxes.length); 
    checkboxes[sorteado].checked=true; //marcar com o check no sorteado
    checkboxes.splice(sorteado,1); //remover o selecionado
  }
}

document.getElementById("sortear").addEventListener("click", function(){
  sortearElementos(3); //aqui passa a quantidade dos elementos a sortear
});
<input type="text" id="resultado">
<input type='checkbox' name='q1_myOptions[]' onclick="add(this)" value="01" id="input_1_1"/>
<label for="input_1_1">01</label>
<input type='checkbox' name='q1_myOptions[]' onclick="add(this)" value="02" id="input_1_2"/>
<label for="input_1_2">02</label>
<input type='checkbox' name='q1_myOptions[]' onclick="add(this)" value="03" id="input_1_3"/>
<label for="input_1_3">03</label>
<input type='checkbox' name='q1_myOptions[]' onclick="add(this)" value="04" id="input_1_4"/>
<label for="input_1_4">04</label>
<input type='checkbox' name='q1_myOptions[]' onclick="add(this)" value="05" id="input_1_5"/>
<label for="input_1_5">05</label>
<button id="sortear">Sortear 3</button>

For simplicity I left in the html only what was referring to the random choice of elements.

    
11.10.2017 / 13:36
1

You can create a list of your options and use the Math .random () to get a random value from it, see the code below, I left it well commented to make it easier to understand.

function add(_this){

  var resultado = document.getElementById('resultado');
  var value = _this.value;
  var hasAdd = resultado.value.search(value) > 0;
  
  if(_this.checked && !hasAdd){
    resultado.value += ' '+_this.value;
  }else if(!_this.checked && hasAdd){
    var er = new RegExp(_this.value, 'ig');
    resultado.value = resultado.value.replace(er, '');
  }
  resultado.value = resultado.value.replace(/ {2,}/g, ' ');
  
}

function random(){
  //Armazeno as suas opções
  var nodeList = document.getElementsByName('q1_myOptions[]');
  
  //limpo o resultado
  document.getElementById('resultado').value = '';
  
  //Percorro suas opções 
  for(i=0;i<nodeList.length;i++){
  
    //Desmarco todos
    nodeList[i].checked = false;
  }
  
  var i = 0;
  while(i<3){
    //Pego um indice aleatorio do array
     var indiceAleatoria = Math.floor(Math.random() * nodeList.length)
    
    var option = nodeList[indiceAleatoria];
    
    //Se a opção ainda não foi sorteada adiciono ela.
    if(option.checked == false){
    
      //Marco a opção sorteada
      option.checked = true;

       //Adiciono a opção sorteada
       add(option);

      i++;
    }
  }

}
input[type=checkbox] {
  display:none;
}
input[type=checkbox] + label {
  color: black;
  border: 1px solid #000;
  padding-left: 10px;
  padding-right: 10px;
  padding-top: 5px;
  padding-bottom: 5px;
}

input#input_1_1:checked + label {
  color: white;
  background-color:#4682B4;
  font-weight: 500;
  border: 1px solid #000;
}

input#input_1_2:checked + label {
  color: white;
  background-color:#4682B4;
  font-weight: 500;
  border: 1px solid #000;
}

input#input_1_3:checked + label {
  color: white;
  background-color:#4682B4;
  font-weight: 500;
  border: 1px solid #000;
}
input#input_1_4:checked + label {
  color: white;
  background-color:#4682B4;
  font-weight: 500;
  border: 1px solid #000;
}
input#input_1_5:checked + label {
  color: white;
  background-color:#4682B4;
  font-weight: 500;
  border: 1px solid #000;
}
#random{
  color: white;
  background-color:#4682B4;
  font-weight: 500;
  border: 1px solid #000;
}
<input type="text" id="resultado">
<input type='checkbox' name='q1_myOptions[]' onclick="add(this)" value="01" id="input_1_1"/>
<label for="input_1_1">01</label>
<input type='checkbox' name='q1_myOptions[]' onclick="add(this)" value="02" id="input_1_2"/>
<label for="input_1_2">02</label>
<input type='checkbox' name='q1_myOptions[]' onclick="add(this)" value="03" id="input_1_3"/>
<label for="input_1_3">03</label>
<input type='checkbox' name='q1_myOptions[]' onclick="add(this)" value="04" id="input_1_4"/>
<label for="input_1_4">04</label>
<input type='checkbox' name='q1_myOptions[]' onclick="add(this)" value="05" id="input_1_5"/>
<label for="input_1_5">05</label>
<div>
  <button type="button" name="random" id="random" onclick="random()">
    3 Aleatórios
  </button>
</div>
    
11.10.2017 / 14:06
0

To the recap !!!

By clicking on the 3 Aleatórios button the script first checks to see if there is checkbox checked. If there are values of checkbox checked are printed in the input of id resultado .

If there is no checkbox checked the random() function is called and 3 constant values of var items are printed in the input of id resultado

$("#random").click(function(){

    var arr = new Array();

    $(":checkbox").each(function(){
      if($(this).is(':checked'))       
      arr.push($(this).val());  
    });
    
    $.each( arr,function(key, value){
       arr = (arr.toString()).replace(new RegExp(',', 'g'), ' ');
       document.getElementById("resultado").value = (arr);
    });
    
    if(arr.length==0){
        random();
    }
    
});

function random() {

   var items = ["01", "02", "03", "04", "05"];
   var newItems = [];

   for(var i = 0; i < 3; i++) {
       var idx = Math.floor(Math.random() * items.length);
       newItems.push(items[idx]);
       items.splice(idx, 1);
   }

   newItems = (newItems.toString()).replace(new RegExp(',', 'g'), ' ');

   document.getElementById("resultado").value = (newItems);

}
input[type=checkbox] {
  display:none;
}
input[type=checkbox] + label {
  color: black;
  border: 1px solid #000;
  padding-left: 10px;
  padding-right: 10px;
  padding-top: 5px;
  padding-bottom: 5px;
}

input#input_1_1:checked + label {
  color: white;
  background-color:#4682B4;
  font-weight: 500;
  border: 1px solid #000;
}

input#input_1_2:checked + label {
  color: white;
  background-color:#4682B4;
  font-weight: 500;
  border: 1px solid #000;
}

input#input_1_3:checked + label {
  color: white;
  background-color:#4682B4;
  font-weight: 500;
  border: 1px solid #000;
}
input#input_1_4:checked + label {
  color: white;
  background-color:#4682B4;
  font-weight: 500;
  border: 1px solid #000;
}
input#input_1_5:checked + label {
  color: white;
  background-color:#4682B4;
  font-weight: 500;
  border: 1px solid #000;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><inputtype="text" id="resultado">
<input type='checkbox' name='q1_myOptions[]' value="01" id="input_1_1"/>
<label for="input_1_1">01</label>
<input type='checkbox' name='q1_myOptions[]' value="02" id="input_1_2"/>
<label for="input_1_2">02</label>
<input type='checkbox' name='q1_myOptions[]' value="03" id="input_1_3"/>
<label for="input_1_3">03</label>
<input type='checkbox' name='q1_myOptions[]' value="04" id="input_1_4"/>
<label for="input_1_4">04</label>
<input type='checkbox' name='q1_myOptions[]' value="05" id="input_1_5"/>
<label for="input_1_5">05</label>
<div>
    <div>  <button type="button" name="random" id="random">
    3 Aleatórios
  </button></div>
    
11.10.2017 / 19:04
0

You can shuffle an array as follows:

var itens = [1,2,3,4,5,6].map(function (item) { 
    return { random: Math.random(), item: item }; 
}).sort(function(objA, objB) {
  return objA.random - objB.random;
}).map(function (obj) {
    return obj.item
});

Here is a complete example:

var valores = document.getElementsByName("valores");
valores = [].slice.call(valores, 0);

var embaralhar = document.getElementById("embaralhar");
embaralhar.addEventListener("click", function (evt) {
  valores.map(function (valor) { 
    return { random: Math.random(), valor: valor }; 
  }).sort(function(itemA, itemB) {
    return itemA.random - itemB.random;
  }).forEach(function (item, indice) {
    item.valor.checked = indice < 3;
  });
})
<label>
  <input type="checkbox" name="valores" value="1" />
  Valor 01
</label>
<br />
<label>
  <input type="checkbox" name="valores" value="2" />
  Valor 02
</label>
<br />
<label>
  <input type="checkbox" name="valores" value="3" />
  Valor 03
</label>
<br />
<label>
  <input type="checkbox" name="valores" value="4" />
  Valor 04
</label>
<br />
<label>
  <input type="checkbox" name="valores" value="5" />
  Valor 05
</label>
<br />
<input type="button" id="embaralhar" value="Embaralhar" />
    
11.10.2017 / 20:28