Home > Software engineering >  How to choose a random text from a set using javascript
How to choose a random text from a set using javascript

Time:09-30

I want to choose a random text from a set using javascript.

I am able make a code which work fine, but work only in choosing a text from 4 different texts.

If I will increase 4 texts to 8 or more than that then the code is not working.

Please help to increase the number of texts

Till now I am able to make this code

var up = document.getElementById('demo');

var safeSet = [
  "https://demo.com/destination-1.html",
  "https://demo.com/destination-2.html",
  "https://demo.com/destination-3.html",
  "https://demo.com/destination-4.html",
  "https://demo.com/destination-5.html",
  "https://demo.com/destination-6.html",
  "https://demo.com/destination-7.html",
  "https://demo.com/destination-8.html"
];

function random(mn, mx) {
  return Math.random() * (mx - mn)   mn;
}

function myFunction() {
  up.innerHTML = safeSet[Math.floor(random(1, 5)) - 1];
}
<textarea id='demo' type='text'></textarea>
<button onclick="myFunction()">Get Text
    </button>

CodePudding user response:

Your random and call to it is not ok.

Also why innerHTML instead of value?

function random(mn, mx) {
  return Math.floor(Math.random() * (mx - mn))   mn; // add the .floor here
}

function myFunction() {
  up.value = safeSet[(random(0,safeSet.length))]; // go from 0 to length
}

var up = document.getElementById('demo');

var safeSet = [
  "https://demo.com/destination-1.html",
  "https://demo.com/destination-2.html",
  "https://demo.com/destination-3.html",
  "https://demo.com/destination-4.html",
  "https://demo.com/destination-5.html",
  "https://demo.com/destination-6.html",
  "https://demo.com/destination-7.html",
  "https://demo.com/destination-8.html"
];

function random(mn, mx) {
  return Math.floor(Math.random() * (mx - mn))   mn;
}

function myFunction() {
  up.value = safeSet[(random(0,safeSet.length))];
}
<textarea id='demo' type='text'></textarea>
<button onclick="myFunction()">Get Text</button>

CodePudding user response:

In your function myFunction you are creating a random number but you are giving a fixed value, here 5. In order to have a random line depending of the numbers of lines in your array I suggest you use the length of safeSet and change the minimum to 0 since the array index start at 0 :

function myFunction() {
   up.innerHTML = safeSet[Math.floor(random(0, safeSet.length))-1];
} 
  • Related