1

My html input number value is not recognized in my J.S code, it alerts Nothing.. the same thing happens if i want to make another code

var age = document.getElementById("ent").value;

document.getElementById("press").onclick = function() {
  alert(age);
}
<input type="number" id="ent">
<button id="press">seed</button>

3
  • 2
    You need to give us more information. Can you show us your HTML as well? Commented Aug 13, 2020 at 19:40
  • You are storing the value of the input when the page loads, before the user types in a value to that input. Commented Aug 13, 2020 at 19:43
  • Move var age = document.getElementById("ent").value; inside the onclick event handler, should fix it. Storing it outside will set the value on load, which would be nothing. Commented Aug 13, 2020 at 19:43

4 Answers 4

7

You're setting age when the page is first loaded, not after the user fills in the input. Assign the variable in the click handler.

document.getElementById("press").onclick = function() {
  var age = document.getElementById("ent").value;
  alert(age);
}
<input type="number" id="ent">
<button id="press">seed</button>

Sign up to request clarification or add additional context in comments.

Comments

0
<html> <head> <title>Quick Coding</title> </head> <body> <input type="number" id="ent"> <button id="press">seed</button> <script type="text/javascript">  document.getElementById("press").onclick = function(){ var age = document.getElementById("ent").value; alert(age); } </script> </body> </html>

Please modify your code as per I've given here. In your code the age value just collecting value at the start of page but tou need to get value after putting data

Comments

0

Alternatively, reflect any change to the input field in the variable as soon as the user inputs anything:

<input type="number" id="ent" oninput="window.age = this.value" >
<button id="press" onclick="alert(window.age)">seed</button>

Comments

0

First, you haven't initialized your input with a value...

 <input type="number" value="80" id="ent">

Second, you can delete all your JS and just inline it directly in the button...

 <button id="press" onclick="alert(ent.value);">seed</button>

3 Comments

i wanted the value to be entered in the input box through the browser itself
It doesn't matter, you must ALWAYS initialize even with a zero!
@user4723924 you do not need to have an initial value. Please test out your code before stating such a strong statement

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.