mardi 16 juin 2015

How do you create a button that will display a random result from an array in javascript?

I've been trying to create a button that will take a random name from an array, and display it on an html page. Been trying for a long while to get this to work, with no results. What gives?

As well, if you know the answer, how could I create another button that would display multiple results, instead of just one?

Thank you in advance!

    <!doctype html>
    <html>
    <head>

    <script>

function postmessage(){
 return "Your new recruit is " + firstnames;


  var firstnames = ["John", "Jacob", "Eric", "Conroy", "Vincent", "Laurence", "Jack", "Harry",    "Richard", "Michael", "Kevin", "Daniel", "Cody", "Brody", "Chase", "Cash", "Norman", "Trevor", "Todd", "Ellis", "Quentin", "Zachary", "Bruce", "Sam", "Horace", "George", "Tom", "Tim", "Wallace", "Walter", "Alex", "Alan", "Sean", "Seamus", "Dudley", "Duke", "Damian", "Nash", "Horton", "Robert", "Mitchell", ];
  var firstnames = firstnames[Math.floor(Math.random() * firstnames.length)];
  var postmessage = "Your new recruit is " + firstnames;
 };
</script>

<meta charset="UTF-8">
<title>Untitled Document</title>
</head>

<body>
<input type="button" value="Get Recruit" onClick="postmessage();"/>
</body>
</html>




Aucun commentaire:

Enregistrer un commentaire