FriedTeddy
FriedTeddy

Reputation: 11

Conditional statement not working - arrays

I have this (novice) JS question:

I have this simple function function movieStorage(), which I want to check if the Yes button is clicked - if so it should storage the output (RandomItem in a new array (movieSaver).

the Output is a random value from the hMovies-array - generated when the Yes button is clicked.

var hMovies = [
  "hMovie1",
  "hMovie18"
];

var movieSaver = [];

var randomItem = hMovies[Math.floor(Math.random() * hMovies.length)];

document.getElementById("buttonYes").addEventListener("click", ifClickedYes);

function ifClickedYes() {
  document.getElementById("showResult").innerHTML = randomItem;
  return (true);
}

function movieStorage() {
  if (ifClickedYes()) {
    movieSaver.push(randomItem);
  }
}
console.log(movieSaver);
<button id="buttonYes">Yes</button>
<div id="showResult"></div>

Upvotes: 0

Views: 60

Answers (1)

Maheer Ali
Maheer Ali

Reputation: 36584

There is no point to check the condition which will be always true. You do not need the second function. The only thing you need is to push the elements to array in the function attached to onclick event.

Also, use generate a new random index on click every time.

var hMovies = [
   "hMovie1",
   "hMovie18"];

var movieSaver = [];
document.getElementById("buttonYes").addEventListener("click", ifClickedYes);

function ifClickedYes(){
  var randomItem = hMovies[Math.floor(Math.random()*hMovies.length)];
  movieSaver.push(randomItem)
  document.getElementById("showResult").innerHTML = randomItem;
  console.log(movieSaver);
}

Working Snippet:

var hMovies = [
   "hMovie1",
   "hMovie18"];

var movieSaver = [];
document.getElementById("buttonYes").addEventListener("click", ifClickedYes);

function ifClickedYes(){
  var randomItem = hMovies[Math.floor(Math.random()*hMovies.length)];
  movieSaver.push(randomItem)
  document.getElementById("showResult").innerHTML = randomItem;
  console.log(movieSaver);
}
<button id="buttonYes">Yes</button>
<div id="showResult"></div>

Upvotes: 1

Related Questions