How to Avoid Decimal Values in Input Type Number

How to restrict from entering a decimal value in input type number?

Preventing user input can be done with JavaScript. I'd use the input event for catching values, as it's a unified interface, encompassing any input method you can think of keyup, paste, pointer events, touch events, etc...

document.querySelector('input').addEventListener('input', e => {
e.target.value = Math.round(e.target.value.replace(/\D/g,''))
});
<input>

Prevent decimal place being entered into input field on mobile

One possible solution:

<script>function onlyNumbers(num){   if ( /[^0-9]+/.test(num.value) ){      num.value = num.value.replace(/[^0-9]*/g,"")   }}</script><input type="text" onkeyup="onlyNumbers(this)">

Allow 2 decimal places in input type=number

Instead of step="any", which allows for any number of decimal places, use step=".01", which allows up to two decimal places.

More details in the spec: https://www.w3.org/TR/html/sec-forms.html#the-step-attribute

HTML5 Number Input - Always show 2 decimal places

Solved following the suggestions and adding a piece of jQuery to force the format on integers:

parseFloat($(this).val()).toFixed(2)

HTML number input: how to allow decimal numbers with step=1

<input type="number" step="any"> step any allow user to enter decimal too and increase by 1.

Input number does not limit decimal when 0 is typed

Resolved the issue with the following code

<input type="number" name="val" min=0 max=9999999999.999999 step=".000001" save="" oninput="validity.valid && ((value.toString()).split('.')[1] === undefined || ((value.toString()).split('.')[1].length < 6)) ? this.save = value : value = this.save"/>

Angular2 input type number, no decimal value

In angular 2 this is very similar to angular1. The takeaway is that it is preferable to keep the logic running within angular because you can trigger/react to other angular events based on the current event, if you ever needed to do so, or if the logic in this class ever was to grow.

The syntax is different but the logic is very much the same—creating a directive that listens to keystrokes.

@Directive({
selector: 'prevent-input',
template: `<input type="text" (keypress)="preventKeyStrokes($event)">`
})

export class PreventInput {
constructor() {}
preventKeyStrokes(event) {
event.preventDefault();
event = event || window.event;
var key = event.keyCode || event.which;
key = String.fromCharCode(key);
var strToTest = '.';
if (/* some regex with '.' */.test(key)) {
return false;
}
}
}

$event is a DOM Keyboard event. Let me know if I can be of any more help.



Related Topics



Leave a reply



Submit