Pregunta

I have very little knowledge of javascript and jquery, but I was able to put the following code together.

I want to add the result of 'name' to the div "displayName" on an html page when I click the "nameCreationButton" button on the html page. When I click "nameCreationButton", absolutely nothing happens.

I declared the variable 'name' outside of the function 'generator', so my jquery should be able to access it, right? I have spent hours looking at this, and I feel silly for not understanding why it will not work.

function generator(){

  var firstName = ["John","Mike","Robert","Patrick"];
  var lastName = ["Smith","Johnson","Williams","Anderson"];

  var randomNumber1 = parseInt(Math.random() * firstName.length);
  var randomNumber2 = parseInt(Math.random() * lastName.length);
  var name = firstName[randomNumber1] + " " + lastName[randomNumber2];
}

var name;

generator();

$(document).ready(function(){
 $(".nameCreationButton").click(function(){
    $(".displayName").append('name');
 });
});

Here is my HTML page if it is any use.

<!DOCTYPE html>
<html>
<head>
    <link rel='stylesheet' href='style.css'/>
    <script type= 'text/javascript' src='nameGenerator_JS.js'></script>
    <script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
</head>
 <body>
    <button class = "nameCreationButton">Click Here to Generate Name</button>
    <div class = "displayName"></div>
 </body>
</html>
¿Fue útil?

Solución

There is absolutely no point in declaring the variable name twice. You do it once inside generator() and once as a global which is not a very good idea.

Instead, what you want is to execute the function generator() once you click on the button. This function needs to return the name.

To rewrite this:

function generator(){
    var firstName = ["John","Mike","Robert","Patrick"],
        lastName = ["Smith","Johnson","Williams","Anderson"],
        randomNumber1 = parseInt(Math.random() * firstName.length, 10),
        randomNumber2 = parseInt(Math.random() * lastName.length, 10);

    return firstName[randomNumber1] + " " + lastName[randomNumber2];
}

$(function(){
    $(".nameCreationButton").click(function(){
        //var name = generator();
        $(".displayName").append(generator());
    });
});

demo

Otros consejos

You need to remove the single ' quote on append('name').

And also you need to remove the var declaration for the name variable inside the generator function. The var name inside the generator block ({ ...}) makes the variable only visible inside that block. So on your original code, you are having two different variables named name with two different scopes.

Try:

function nameGenerator(){

  var firstName = ["John","Mike","Robert","Patrick"];
  var lastName = ["Smith","Johnson","Williams","Anderson"];

  var randomNumber1 = parseInt(Math.random() * firstName.length);
  var randomNumber2 = parseInt(Math.random() * lastName.length);
  return firstName[randomNumber1] + " " + lastName[randomNumber2];
}


$(document).ready(function(){
 $(".nameCreationButton").click(function(){
    var name = nameGenerator();
    $(".displayName").text(name);
 });
});

(*) you had rfered variable with quotes, it will be considered a string

 var name = "aslan";
 console.log(name) //=> aslan
 console.log("name") //=> name

(*) also, variable name is declared inside and out side function. variable declared inside function is considered as local variable, so var name declared outside function wont get update, which us used append(). check : http://snook.ca/archives/javascript/global_variable

Change code to:

 function generator(){

   var firstName = ["John","Mike","Robert","Patrick"];
   var lastName = ["Smith","Johnson","Williams","Anderson"];

   var randomNumber1 = parseInt(Math.random() * firstName.length);
   var randomNumber2 = parseInt(Math.random() * lastName.length);
   return  firstName[randomNumber1] + " " + lastName[randomNumber2];
 }


 $(document).ready(function(){
   $(".nameCreationButton").click(function(){
      $(".displayName").append( generator() );
   });
 });
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top