Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pick a random item from a list

I'm learning Javascript and i need some help. I have a list. I've tried to make a list, where you can, by the click of a button, get a random song from that list, but it doesn't seem to work. My list is down below, what am i doing wrong?

<!DOCKTYPE html>
<html>
<head>
</head>
<body>

<div>
  <button type="randomSong">Random Music</button>
  <input "randomSong" id="randomSong">
</div>

<script>

var song = Array("song1", "song2", "song3", "song4", "song5", "song6");

var randomSong = song[Math.floor(Math.random()*song.length)];

</script>

</body>
</html>
like image 243
Martin Grønne Avatar asked Sep 18 '25 18:09

Martin Grønne


1 Answers

Your code is almost correct. Here is a proper version:

HTML

<div>
  <button type="randomSong" onclick="randomSong()">Random Music</button>
  <input name="randomSong" id="randomSong">
</div>

Modifications:

  • add an attribute name to the input (you had "randomSong" without any attribute key)
  • use an onclick callback, so that something happens when you click your button

JS

var song = Array("song1", "song2", "song3", "song4", "song5", "song6");

function randomSong() {
  var randomSong = song[Math.floor(Math.random() * song.length)];
  document.getElementById('randomSong').value = randomSong;
}

Modifications:

  • wrap your random code into a function (the one referenced by the onclick attribute of your button)
  • assign the result to the input
like image 50
Derlin Avatar answered Sep 21 '25 07:09

Derlin