Home > Software design >  How can i get a input number value in javascript?
How can i get a input number value in javascript?

Time:04-05

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.

CodePudding user response:

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

CodePudding user response:

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

CodePudding user response:

.value returns a string. Use parseInt(x, 10) or parseFloat.

CodePudding user response:

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" />

CodePudding user response:

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>

  • Related