Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

286
Vistas
How can I get a random item from multiple arrays based on a checkbox?

I want to only show the text from the arrays that are selected with the checkboxes (so, if i only want txt and ran, it only shows options from those arrays)

function myFunc() {
  let txt = ["txt1", "txt2", "txt3"];
  let test = ["test1", "test2", "test3"];
  let ran = ["ran1", "ran2", "ran3"];

  let tst = txt[Math.floor(Math.random() * txt.length)] + "<br><br><br>" + test[Math.floor(Math.random() * test.length)] + "<br><br><br>" + ran[Math.floor(Math.random() * ran.length)];
  document.getElementById("tst").innerHTML = tst;
}
<input type="checkbox"> txt<br>
<input type="checkbox"> test<br>
<input type="checkbox"> ran
<br>
<br>

<button onclick="myFunc()">One Character</button>

<p id="tst">
  sum text lol
</p>

Code: https://jsfiddle.net/RoseLovesGreene/ps17u8yd/6/

I'd also like to be able to show it in a random order so that each array doesn't have it's own line.

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

You could use an if clause to determine whether or not the checkbox is checked. Then if it is checked, use the random number as a key to the array, which you can then append to the result.

 function myFunc() {
     

     let txt = ["txt1", "txt2", "txt3"];
     let test = ["test1", "test2", "test3"];
     let ran = ["ran1", "ran2", "ran3"];

     let target = document.getElementById('tst');
     
     let result = "";
     
     let txtKey = [Math.floor(Math.random() * txt.length)]
     let testKey = [Math.floor(Math.random() * test.length)]
     let ranKey = [Math.floor(Math.random() * ran.length)]
     
     
        if (document.getElementById('txt').checked) {
     result = result+txt[txtKey];
     }
     
        if (document.getElementById('test').checked) {
     result = result+test[testKey];
     }
     
        if (document.getElementById('ran').checked) {
     result = result+ran[ranKey];
     }



target.innerHTML = result;
     
     
 }
<input id="txt" type="checkbox"> <label for="txt">txt</label><br>
<input id="test" type="checkbox"> <label for="test">test</label><br>
<input id="ran" type="checkbox"> <label for="ran">ran</label>
<br>
<br>

<button onclick="myFunc()">One Character</button>

<p id="tst">
sum text lol
</p>

There are a few things that you could do to make this more elegant, but I think the idea works.

about 4 years ago · Juan Pablo Isaza Denunciar

0

To get the values of your checkboxes, you need to give them actual values - and to reference the arrays without a bunch of IF statements, they need to be referencable in something like an object.

This will get random values from each array as it loops the forEach, but the final output needs to be shuffled (per your spec). There are many ways of doing this - I grabbed one of the more concise versions, but there are many to choose from here: How to randomize (shuffle) a JavaScript array?

function shuffle(a, b, c, d) { //array,placeholder,placeholder,placeholder
  c = a.length;
  while (c) b = Math.random() * (--c + 1) | 0, d = a[c], a[c] = a[b], a[b] = d;
  return a
}

function myFunc() {
  let vars = {
    txt: ["txt1", "txt2", "txt3"],
    test: ["test1", "test2", "test3"],
    ran: ["ran1", "ran2", "ran3"]
  }

  // get the checked values into an array
  let flatArr = [];
  document.querySelectorAll('[type=checkbox]:checked').forEach(el => {
      flatArr = [...flatArr, vars[el.value][Math.floor(Math.random() * vars[el.value].length)]]
      });
    document.getElementById("tst").innerHTML = shuffle(flatArr).join(" ");
  }
<input type="checkbox" value='txt'> txt<br>
<input type="checkbox" value='test'> test<br>
<input type="checkbox" value='ran'> ran
<br>
<br>

<button onclick="myFunc()">One Character</button>

<p id="tst">
  sum text lol
</p>

about 4 years ago · Juan Pablo Isaza Denunciar

0

//Object of arrays
let options = {
  txt : ["txt1", "txt2", "txt3"],
  test : ["test1", "test2", "test3"],
  ran : ["ran1", "ran2", "ran3"]
};

function myFunc() {

  //Get all checkboxes
  let checkedBoxes = document.querySelectorAll('input[type=checkbox]:checked');
  
  //array for texts from arrays
  let texts = [];
  
  //loop through selected checkboxes
  checkedBoxes.forEach(function(ele) {
  
    // select respective array from object based on checkbox value
    let cOpt = options[ele.value];
    
    // random index for texts array - to randomize array text line
    let index = Math.floor(Math.random() * checkedBoxes.length);
    
    // to make sure we didn't set a text to that index already
    while( texts[index] !== undefined ) {
      index = Math.floor(Math.random() * checkedBoxes.length);
    }
    
    // set selected array text to a random index in texts array
    texts[index] = cOpt[Math.floor(Math.random() * cOpt.length)];
    
  });

  // text.join() to covert texts array into string
  document.getElementById("tst").innerHTML = texts.join('<br><br>');

}
<input type="checkbox" value="txt"> txt<br>
<input type="checkbox" value="test"> test<br>
<input type="checkbox" value="ran"> ran<br>

<button onclick="myFunc()">One Character</button>

<p id="tst">
sum text lol
</p>

You need to make some adjustments in your approach. i.e set values to checkboxes, create a js obj with all arrays being its property.

Make sure checkboxes values and properties keys are the same.

I have added comments in the code so you can easily understand the purpose of each line.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda