Luke Sheldon
Luke Sheldon

Reputation: 23

HTML onclick only working once with JavaScript

As said above. Here is an example of the kind of code I am trying to use:

http://codepen.io/anon/pen/LGLJXd

<button id='myButt' onclick='randGen()'>New Target</button>
<button id="myOtherButt" onclick='clear()'>Clear</button>

<p id='test'>Click me to randomly choose from the array!</p>

And then JS;

var myArray = ["Empire", "Rebels", "Scum", "Clones", "Trade Federation", "Sith", "Jedi"];
var rand = myArray[Math.floor(Math.random() * myArray.length)];

function randGen() {
  document.getElementById('test').innerHTML = rand;
}; 

function clear() {
  document.getElementById('test').innerHTML = 'No';
};

It works well once, but 'clear' or trying to use the First button more than once is not responsive. Could someone help me understand what I'm not doing right?

Upvotes: 1

Views: 1686

Answers (3)

Daniel Bauer
Daniel Bauer

Reputation: 168

The problem here is that you initialize the property "rand" only at the beginning. So everytime you call the function "randGen()" the "rand" property uses the same value.

To always get a new value you also have to set rand to a new value.

The solution is that simple:

function randGen() {
  // get a new value
  var rand = myArray[Math.floor(Math.random() * myArray.length)];

  // set the value
  document.getElementById('test').innerHTML = rand;
}; 

Upvotes: 0

Arnaud Gueras
Arnaud Gueras

Reputation: 2062

You are calling rand that is only a variable that was generated one time.

If you want to get another random item, you should use a function that returns the result :

function rand() {
    var myArray = ["Empire", "Rebels", "Scum", "Clones", "Trade Federation", "Sith", "Jedi"];
    return myArray[Math.floor(Math.random() * myArray.length)];
}
function randGen() {
  document.getElementById('test').innerHTML = rand();
}; 

function clear() {
  document.getElementById('test').innerHTML = 'No';
};

Upvotes: 2

Konstantin Dinev
Konstantin Dinev

Reputation: 34895

You have generated your random once when the page is loading and it never changes. In order for it to change you need to generate it again on click:

var myArray = ["Empire", "Rebels", "Scum", "Clones", "Trade Federation", "Sith", "Jedi"];

function randGen() {
    var rand = myArray[Math.floor(Math.random() * myArray.length)];
    document.getElementById('test').innerHTML = rand;
}; 

Upvotes: 4

Related Questions