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

Can't get resault to show in this JS function.

I'm supposed to make a simple input field take in a number from the user, when you hit the button, it should show the number of boxes that the user typed in to the number input field

Here is a link to my CodePen http://codepen.io/anderslund007/pen/qreOWb?editors=1111

Can anyone see what im doing wrong? Thanks

2 Answers

Hey, I checked your code out (mainly your javascript). The one main thing I noticed in the line "var inputNum = document.getElementById("myInt").value;" is incorrectly placed.

It needs to be assigned within the onclick function that will get the current value of the number entered into the input field.

Here is a javascript code that worked closer to what you maybe wanted. Although one problem may be it continues to add more divs without getting rid of the previously added div. Check it out. I hope it gets closer to what you were wanting to do.

var html = '';
var inputNum;

function myFun(){
  inputNum = document.getElementById("myInt").value;
  for ( var i = 0; i < inputNum; i += 1){
    html += '<div>' + i + '</div>';
  }
  document.getElementById("color").innerHTML += html;
}

Okey, thanks :) But, why do the "var inputNum = document.getElementById("myInt").value" has to be declared inside the function? cant I do it in the global scope then call the var name and use it in the function?

The reason why it has to be declared within the function is because the onclick function "myFun()" is called every time anyone clicks the button. Where as the code outside in the global space is called once, and is not called every time someone clicks the button.

So, if you declare it outside the onclick function, in the global space, it would only declare it once at the beginning when the page is loaded. Whereas with it declared inside the function it will be re-declared to whatever value the input has every time the user clicks the button.

Hope this helps.

Okey, thanks :)