0

I have an input field which is of number type, when I enter the dot I am not getting the value. So what I am trying to achieve is the I don't want the user to enter dot on the input field

function handleChange (value) {
 console.log(value)
}
<input type="number" onchange="handleChange(this.value)"/>

on each number entering I am getting the value, but when I type dot (.), I am not getting how can I block this when user type it

dev
  • 814
  • 10
  • 27
  • 2
    The code snippet you shared does exactly what you asked for . what is the problem ? – nermineslimane Dec 10 '21 at 11:29
  • Why dont you use some jquery to set the the value to '' when the user types a dot – Dimitris Papageorgiou Dec 10 '21 at 11:32
  • Does this answer your question? [HTML input for Positive Whole Numbers Only (Type=number)](https://stackoverflow.com/questions/32777184/html-input-for-positive-whole-numbers-only-type-number) – vatz88 Dec 10 '21 at 11:33
  • the type number does not exclude decimal numbers, thus avoiding the . might be fatal since typing in 2.4 is a valid input. If you try to put a dot after the 2.4 you will realize this does not work anymore, since a number does not have 2 dots. This is a completely intentional behaviour – Branchverse Dec 10 '21 at 11:34

4 Answers4

1

if you want to block '.' you can use this way,

function handleChange (value) {
console.log(value)
}

var inputBox = document.getElementById("inputBox");

var invalidChars = [
".",

];

inputBox.addEventListener("keydown", function(e) {
  if (invalidChars.includes(e.key)) {
    e.preventDefault();
  }
});
<input type="number" id="inputBox" onchange="handleChange(this.value)/>
Junaid Shaikh
  • 1,045
  • 4
  • 19
0
<input name="num" type="number" min="1" step="1" onkeypress="return event.charCode >= 48 && event.charCode <= 57">

referance from this url https://stackoverflow.com/a/44379790/4316212

0

Add This oninput="this.value = this.value.replace(/[^0-9]/, '')"

function handleChange (value) {
 console.log(value)
}
<input type="number" onchange="handleChange(this.value)" oninput="this.value = this.value.replace(/[^0-9]/, '')"/>
Lalji Tadhani
  • 14,041
  • 3
  • 23
  • 40
0

It is generally not a good idea to use inline event handlers.

For more control you should check/use the atributes of a number input.

If you want to completely control the input, use a readonly field and handle it using your own handler. Here's a snippet using event delegation. It uses the step attribute from the number input field for adding/subtracting.

document.addEventListener('click', handle);

function handle(evt) {
  if (evt.target.dataset.numinput) {
    const inp = document.querySelector(`#num`)
    inp.value = ( +inp.value +  +(`${evt.target.dataset.numinput}${inp.step}`) )
      .toFixed(2);
  }
}
<input id="num" type="number" step="0.1" readonly/>
<button data-numinput="-"> - </button>
<button data-numinput="+"> + </button>
KooiInc
  • 119,216
  • 31
  • 141
  • 177