Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Making button accept text input Javascript

Hello,

I am trying to make a "Guess the Number" game.

A user simply has to enter a number into a number field.

How do I make the "Submit" Button pass the iinputed number into a variable I declared already?

3 Answers

Jonathan Grieve
MOD
Jonathan Grieve
Treehouse Moderator 91,254 Points

Let's look at it line, by line, assuming your code is now the same as what's on CodePen.

var number = Math.floor(Math.random() * 10) + 1;
var button = document.getElementById('checkNumber');

button.addEventListener('click', function(){
  var inputNumber = document.getElementById('number');
  if (inputNumber.value == number) {
    inputNumber.value = 'Yay! ' + number + ' is correct!';
    number = Math.floor(Math.random() * 10) + 1;
  } else {
    inputNumber.value = '';
  }

});

We've got 2 variables here, one that stores a random number between 1 and 10. Since by flooring (Math.floor()) the number (rounding it down) it's actually only 1-9 so we add another number to the expression.

var button is simply letting the browser know we want to do something with the button and making sure we do something with the correct button and we do that with given id of the button element.

So next we reference the getElementById and assign it to anonymous function which wants a click action.

Inside it as where the action happens. We want to compare the users's input with the result of the random number between one and ten. If we get it right, you get the congratulatory message. If not, what the code does is provide an empty sting that clears out the input form so you can try again.

At the heart of it all is a condition statement. The expression is comparing the number given, that you provided and comparing that to the value that Math.random() generates.

I hope this makes sense to you. :-)

Add a event listener to the button which listens for click, store the correct number globally outside the function which gets called when a user clicks on the button. Inside this function read the value of the textbox. An example can be found here: http://codepen.io/anon/pen/EajYKR

Thanks a lot. I copied the code, it's partly functional.

However, I don't understand how it works