'How can i get a input number value in javascript?
I want to get the value of a input with the type of number. Here is the HTML
<input type="number" id="number" value="1">
and here is the javasript
const number = document.getElementById('number').value;
when i try to console.log(number) the result is 1 but when i increace the value of the input the result is still 1.
When i want to console.log(number) i want the result to be 1 but when i increase the value of the input like 3 i want the result to be 3.
Solution 1:[1]
Maybe you can add a submit button to add it and use the following script:
const numberInput = document.getElementById("number");
const buttonAdd = document.getElementById("add");
let number = numberInput.value;
buttonAdd.addEventListener("click", (event) => {
number = ++number;
console.log(number);
numberInput.value = number;
})
<input type="number" id="number" value="1"/>
<input type="submit" id="add" value="Add"/>
Solution 2:[2]
Basically, all input field values are string, so
const number = document.getElementById('number').value;
// number = "1"
Try adding parseInt to make it an integer:
const number = parseInt(document.getElementById('number').value);
// number = 1
Solution 3:[3]
You also have to update the DOM-element if you want to see the result.
const number = document.getElementById('number').value
number += 2
document.getElementById('number').value = number
Solution 4:[4]
.value returns a string. Use parseInt(x, 10) or parseFloat.
Solution 5:[5]
I believe you want to update the number when it changes. Consider adding an event listener to the input element. Such that it updates the number variable every time you change it's value.
const numberInput = document.getElementById("number");
let number = numberInput.value;
numberInput.addEventListener("change", (event) => {
number = event.target.value
console.log(number)
})
<input type="number" id="number" value="1" />
Solution 6:[6]
When you code:
const number_at_instant_time = document.getElementById('number').value;
You get only the string value in the input present at this moment.
if the input value change, the value number_at_instant_time will stay at the same value
so correct code should be:
Coding also means reading up-to-date documentation
const myNumber = document.querySelector('#my-number');
document.querySelector('#bt-get-num').onclick = () =>
{
console.clear();
let strVal = myNumber.value;
let numVal = myNumber.valueAsNumber;
console.log('strVal + 15 = ', strVal + 15 )
console.log('numVal + 15 = ', numVal + 15 )
}
<input type="number" id="my-number" value="1">
<br>
<button id="bt-get-num"> Get number value</button>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Diar J R |
| Solution 2 | |
| Solution 3 | Tobias S. |
| Solution 4 | nedoder |
| Solution 5 | Ammiel Yawson |
| Solution 6 |
