Prasad_Joshi
Prasad_Joshi

Reputation: 662

How to get random array element onclick of a button in Javascript

I have a java script array with large number of elements inside it, on click of a button I want to display the any random array element on screen, for which I have used Math.random function, but not sure why it is not working. here is my code below.

<html>
  <head>
    <title>Demo</title>
  </head>
  <body>
    <button id="getquotes" value="Quotes" onclick="Loadquotes();">Quotes</button>
    <p id="quoteshere" ></p>
    <script>
      var Loadquotes= function(){
        var quotes = new Array('Stack1','Stack2','Stack16','Stack17','Stack13','Stack14','Stack15','Stack6','Stack7','Stack8','Stack9','Stack10');
        var i;

        for (i=0;i<quotes.length;i++){
          var newquotes = quotes[Math.floor(Math.random() * quotes.length)];
          document.getElementById('quoteshere').value=newquotes;
        }
      };
    </script>
  </body>
</html>

Upvotes: 1

Views: 2472

Answers (3)

Dhirendra
Dhirendra

Reputation: 309

Try This

<html>
<head>
    <title>Demo</title>
</head>
        <body>
                <button id="getquotes" value="Quotes" onclick="Loadquotes()"> Quotes </button>
                    <p id="quoteshere" ></p>
                        <script>
                function Loadquotes(){
                var quotes = new Array('Stack1','Stack2','Stack16','Stack17','Stack13','Stack14','Stack15','Stack6','Stack7','Stack8','Stack9','Stack10');
                var newquotes = Math.floor(Math.random() * quotes.length);
                document.getElementById('quoteshere').innerHTML = quotes[newquotes];

                 }
                        </script>
        </body>

Upvotes: 0

arunkumar talla
arunkumar talla

Reputation: 157

you can try this

var quotes = Array('Stack1','Stack2','Stack16','Stack17','Stack13','Stack14','Stack15','Stack6','Stack7','Stack8','Stack9','Stack10');
var Loadquotes= function(){
    var newquotes = quotes[Math.floor(Math.random() * quotes.length)];
    document.getElementById('quoteshere').innerHTML=newquotes;
};
<button id="getquotes" value="Quotes" onclick="Loadquotes();">Quotes</button>
<p id="quoteshere" ></p>

Upvotes: 1

Curiousdev
Curiousdev

Reputation: 5778

quoteshere is P Tag value function won't work use innerText or innerHTML instead please find below snippet

var Loadquotes= function(){
  debugger;
  var quotes = new Array('Stack1','Stack2','Stack16','Stack17','Stack13','Stack14','Stack15','Stack6','Stack7','Stack8','Stack9','Stack10');
  var i;

  for (i=0;i<quotes.length;i++){
    var newquotes = quotes[Math.floor(Math.random() * quotes.length)];
    document.getElementById('quoteshere').innerText = newquotes;
  }
};
<button id="getquotes" value="Quotes" onclick="Loadquotes();">Quotes</button>
<p id="quoteshere" ></p>

Upvotes: 2

Related Questions