Question

I'm trying to get a random name from my array to display once the button is clicked. In the console I get "Uncaught ReferenceError: arry is not defined" which I assume is because arry is not a global variable. How can I remedy this situation?

jsbin

var randomName = function() {
  arry = ["Kevin", "John", "Mabel", "Lucy", "Isabella", "Ryan", "Clyde"];
    var random = arry[Math.round(Math.random() * arry.length)];
    return random;
};

// create button
var button = document.createElement("input");
var id = "btn";
  button.type = "submit";
  button.value = "click me!";
  button.setAttribute("id", "btn");

document.body.appendChild(button);

// initialize function
window.onload = function() {
// add event listener
  document.getElementById("btn").addEventListener("click", function(e) {
    document.getElementById("name").innerHTML = arry[0].random;
     console.log("hi");
    }   
  );
};
Was it helpful?

Solution

Change this line:

document.getElementById("name").innerHTML = arry[0].random;

to this:

document.getElementById("name").innerHTML = randomName();

Working demo: http://jsbin.com/xugeg/1

You created the function randomName() to fetch a random value from your array and all you need to do is to call it.

arry[0].random; is wrong because arry[0] is a string and does not have a property named random.

OTHER TIPS

Why not just use your existing randomName() function?

Simply replace this line

document.getElementById("name").innerHTML = arry[0].random;

with

document.getElementById("name").innerHTML = randomName();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top