0

I want to change the content of a div randomly by .InnerHTML. The text are saved as variables. The random number is another variable. The Problem is, that if I put text and random number together it will print text1 for example.

Can someone help me with that?

function switchText(){
var text1 = "hello";
var text2 = "there";
var text3 = "ObiWan";

var randomNumber = Math.floor(Math.random() * 3) + 1;//creates random No. from 1 - 3

document.getElementById("randomText").innerHTML = "text" + randomNumber;
//the problem
}
<div id="randomText" onclick="switchText();">click here</div>
Wai Ha Lee
  • 8,598
  • 83
  • 57
  • 92
  • `document.getElementById("randomText").innerHTML = eval("text" + randomNumber);` ... (I'm joking) – Lennholm Feb 18 '18 at 20:55
  • Probably a duplicate of [*Use dynamic variable names in JavaScript*](https://stackoverflow.com/questions/5117127/use-dynamic-variable-names-in-javascript) or [*How do I create dynamic variable names inside a loop?*](https://stackoverflow.com/questions/8260156/how-do-i-create-dynamic-variable-names-inside-a-loop) – RobG Feb 18 '18 at 20:57

4 Answers4

2

How about storing all random strings in an array, like so:

function switchText(){
    var randomWords = ["hello", "there", "ObiWan"];

    var randomIndex = Math.floor(Math.random() * 3);//creates random No. from 1 - 3

    document.getElementById("randomText").innerHTML = randomWords[randomIndex];
    //the problem
}
Varinder
  • 2,634
  • 1
  • 17
  • 20
1

Actually you can access those variables by using index notation (it's described really nicely here) so in your specific case of function you just need to change the line where you try to access the variable to

document.getElementById("randomText").innerHTML = this['text' + randomNumber];

However though such notation is not something I would recommend. Usage of array as it was suggested is much more readable in fact.

Tomasz Kapłoński
  • 1,320
  • 4
  • 24
  • 49
0

Your question is focused on how to dynamically construct a variable name, but usually this problem comes up because the solution you are attempting is based on a coding pattern that has boxed you into a corner. Instead of writing a potentially hazardous solution or one that is overly complex, re-think your approach.

Whenever you have several pieces of data to store that don't have key names to go with them, you should be storing those data in an Array. The advantages to storing data in an array are huge. So, you should place the strings into an array instead of individual variables that all have to have similar names. So, now you have less variables to worry about and no variable names that have to be set to certain values and the problem of dynamically creating a variable name is gone entirely.

All you need to do now is to use the random number as an index to the array. Don't adjust the random to make it 1-based, because arrays are 0-based. And, when you get the random, multiply it by the length of the array, rather than hard code a number. This way, all you have to do is add/remove strings to the array for them to become possible resulting strings.

This structure and solution make your code simpler and more flexible.

Also, don't set up your event handlers using HTML event attributes. There are many reasons why you shouldn't use this 25+ year old technique. Do it in JavaScript.

var strings = ["hello","there","ObiWan"];  // Store the possible strings in an array

var btn = document.getElementById("randomText");  // Get a reference to the trigger element
var output = document.getElementById("output");   // And the output area

// Set up the event handler in JavaScript, not HTML
btn.addEventListener("click", function(){
  // Set the output to a string from the array using a random index
  output.innerHTML = strings[Math.floor(Math.random() * strings.length)];
});
<button id="randomText">click here</button>
<div id="output"></div>
Scott Marcus
  • 64,069
  • 6
  • 49
  • 71
0
  • Store those texts into an array and use the random number.
  • Get the random number as follow: Math.floor(Math.random() * 3)

function switchText(){
var texts = ["hello", "there", "ObiWan"];

var randomNumber = Math.floor(Math.random() * 3);//creates random No. from 1 - 3
console.log(randomNumber)
document.getElementById("randomText").innerHTML = texts[randomNumber];
//the problem
}
<div id="randomText" onclick="switchText();">click here</div>
  • You can store those texts into an object as well.

function switchText() {
  var texts = {
    "text1": "hello",
    "text2": "there",
    "text3": "ObiWan"
  };

  var randomNumber = Math.floor(Math.random() * 3) + 1; //creates random No. from 1 - 3
  console.log(randomNumber)
  document.getElementById("randomText").innerHTML = texts[`text${randomNumber}`];
  //the problem
}
<div id="randomText" onclick="switchText();">click here</div>
Ele
  • 33,468
  • 7
  • 37
  • 75