0

newbie here and I've created this javascript program where when the user enters a number greater than 21 a alert pops up saying they're legal, of if the number is less than, another alert pops up saying they are too young. I'm not sure if I'm using the onclick event the right way. But when I click the button nothing happens, but when i reload the page then the alerts pop up. Not sure whats wrong, any suggestions? Thanks in Advance.

Here is my code

var button = document.getElementById("button").onclick = legal(); 

function legal(){
 var input = document.getElementById("input").value; 
  var age = 21; 
  
  if(input < age){
    alert("Sorry, your not old enough");
  }
  else{
   alert("Great, come on in! your legal");
  }
}
<h1>
  Are you Legal?
</h1>

<input type="number" id="input">
<button id="button" onclick="legal();">submit</button>
Ajea Smith
  • 15
  • 3
  • 1
    You know the difference between function call and function reference? – Teemu Feb 23 '18 at 16:17
  • You shouldn't need the first line of js in your code since you are setting the onclick as an attribute in your html element. Especially if you are loading that js block in the head of your html file, it won't know what a button is unless you load the button first – Tim Joyce Feb 23 '18 at 16:25
  • Thanks for the quick responses guys, that helped me alot. I'm not familiar with difference between function call and function reference but I'm surly going to look that up. – Ajea Smith Feb 23 '18 at 16:57

1 Answers1

1

You may not execute the function while adding it as the listener's callback:

var button = document.getElementById("button").onclick = legal; 

function legal(){
 var input = document.getElementById("input").value; 
  var age = 21; 
  
  if(input < age){
    alert("Sorry, your not old enough");
  }
  else{
   alert("Great, come on in! your legal");
  }
}
<h1>
  Are you Legal?
</h1>

<input type="number" id="input">
<button id="button" onclick="legal();">submit</button>

Edit from the comment (by @Peter Van Drunen):

by putting parentheses next to your function, you are making it into a function call rather than a function reference. When assigning a handler, you obviously don't want to call the function, only reference it. So all you need is the name of the function without parentheses.

messerbill
  • 5,499
  • 1
  • 27
  • 38
  • To expand in this: by putting parentheses next to your function, you are making it into a function _call_ rather than a function reference. When assigning a handler, you obviously don't want to call the function, only reference it. So all you need is the name of the function without parentheses. – Peter Van Drunen Feb 23 '18 at 16:22
  • Thanks Peter, I didn't realize the difference between the two – Ajea Smith Feb 23 '18 at 17:09