Categories
JavaScript Answers

How to avoid decimal values in a number input with JavaScript?

Spread the love

To restrict a number input to accept only whole numbers (integers) without decimal values, you can use JavaScript to listen for the input event and validate the input value. Here’s an example of how you can achieve this:

<input type="number" id="myNumberInput">

to create an HTML input.

Then write the following JavaScript code

<script>
document.getElementById('myNumberInput').addEventListener('input', function(event) {
    // Get the input value
    let inputValue = event.target.value;
    
    // Remove any non-numeric characters and leading zeroes
    inputValue = inputValue.replace(/\D|^0+/g, '');
    
    // Update the input value
    event.target.value = inputValue;
});
</script>

In this code we attach an event listener to the number input element with the ID myNumberInput.

When the input event is triggered (i.e., when the user types or pastes into the input field), the event listener function is called.

Inside the event listener function, we retrieve the input value from the event object.

We use a regular expression (/\D|^0+/g) to remove any non-numeric characters and leading zeroes from the input value.

Finally, we update the input value to the sanitized value without decimal values.

This code will ensure that only whole numbers are accepted in the number input field, and any decimal values will be automatically removed as the user types.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *