[SOLVED] How can I get a random item from multiple arrays based on a checkbox?

Issue

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.

Solution

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>

Answered By – Kinglish

Answer Checked By – David Marino (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *