How to create a button that randomly selects 3 out of 5 numbers

Asked

Viewed 102 times

2

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

follows 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>

4 answers

2

I suggest you build an array with the elements that are yours inputs of the kind checkbox. Then make a loop for the amount of elements you want to draw and check each element drawn and remove from the array so you can’t exit 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 html only what was related to the random choice of elements.

  • Interesting way to use spread to array the elements.

  • @dsantoro It is indeed not detailed that part in the answer, but it is one of the most direct ways to convert from a NodeList which is what comes out of querySelectorAll for Array. Although many things are possible to use directly in a NodeList such as a forEach some not so much as the splice

  • always used this way: var myVar = [].slice.call(Document.querySelectorAll('selector')); but this approach is interesting, but only used with some transpiler right.

  • @dsantoro It will end up being the same. The way I used it is a little more ES6 and shorter, but it remains native js.

1

You can create a list of your options and use the function Math.() to pick up a random value from it, see the code below, I left it well commented to facilitate understanding.

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>

  • Cool, although I already have an answer with the exact idea. When we click on the button that randomizes the input is filled every time accumulating thus not only 3 drawn numbers but 3 n

  • Thank you guys, you helped me a lot! Solved the problem with your solutions!

  • Magina I thank, I learned several things responding :)

0

I’m in the repechage!!!

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

If there is no checkbox marked the function random() is called and 3 random values are printed var items in the id input 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>

<input type="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>

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

below 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" />

Browser other questions tagged

You are not signed in. Login or sign up in order to post.