JavaScript

Allow only numbers to enter in the HTML input – Javascript

Share your learning

Today I am going to discuss the most common asked problem, allow only numbers to enter in the HTML input.

But before that let’s understand our purpose.

Why need to enter numbers only in the html input?

  1. If you want to show an error message on input hover or on submit the form about invalid input. You can use HTML input pattern, input type tel, number etc.
  2. If you want that user must not be able to enter invalid inputs. Like if you have created an input for numbers then it must accept numbers only. Then you need JavaScript solutions.

Check the codepen Demo.

Basic solutions are

Pattern attribute of HTML 5 Input

  1. Simple input type or using pattern attribute of HTML input

    As of now HTML 5 supports regular Expression as a pattern attribute to the input field, we can use that too. But it’s not fully supported with all browsers.
<input id="patternAttr" pattern="[0-9.]+" type="text">

Or

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

Input type Tel

  1. Even if you want that device to automatically show the keyboard according to requirements like numeric keyboard for number fields.
<input id="phoneInput" type="tel" name=”telephone_number” />

For other solutions we have to use JavaScript. That means no one can input invalid values; it will allow only numbers to enter in the HTML input.

JavaScript solutions to allow only numbers

Step 1.

Create a function where we will pass the two parameters one will be input field and another will be callback function.

This function will include all the possible events on the input field and add the JavaScript listeners for them.

This is a one time process, after this, this method will take care of everything.

function setInputFilter(textbox, inputFilter) {
  ["input", "keydown", "keyup", "mousedown", "mouseup", "select", "contextmenu", "drop"].forEach(function(event) {
    textbox.addEventListener(event, function() {
      if (inputFilter(this.value)) {
        this.oldValue = this.value;
        this.oldSelectionStart = this.selectionStart;
        this.oldSelectionEnd = this.selectionEnd;
      } else if (this.hasOwnProperty("oldValue")) {
        this.value = this.oldValue;
        this.setSelectionRange(this.oldSelectionStart, this.oldSelectionEnd);
      } else {
        this.value = "";
      }
    });
  });
}

Step 2.

Now just setup the input filter for your input field. We can use this filter as many times as we want.

setInputFilter(document.getElementById("numbersOnly"), function(value) {
  return /^\d*\.?\d*$/.test(value); 
});

It is using regular Expression to allow only numbers and dots to enter in the HTML input.

Inline JavaScript to make simpler solution

Inline Js with regular Expression

We can use the oninput attribute of HTML input to listen to the changes of the field value. As the onchange event needs focus out of the input field to trigger, oninput can detect the changes while typing the data into it.

Here is the browser support for the oninput attribute.

<input type="text" oninput="this.value = this.value.replace(/[^0-9.]/g, '').replace(/(\..*?)\..*/g, '$1');" />

Some jQuery solutions

Let’s see some basic and useful jQuery solutions to allow only digits to enter in the HTML input field. Best point is you don’t need to remember regular Expression pattern here. We are going to use the isNaN() function to identify non-numeric values.

$('body').on('propertychange input', 'input[type="text"]', function() {
    var inputVal = $(this).val();
    if( isNaN(Number(inputVal)) ) {
          this.value = this.hasOwnProperty("oldValue") ? this.oldValue : '';
    } else {
          this.oldValue = inputVal;
    }
});

It can prevent copying non-numeric values to the input field. Allow for single decimal point and also control the drag and drop non-numeric content to this input field.

Hope you find this article useful. Please share your opinion in the comment section below.

If you have learned any other method to achieve the same, do comment below. I will add that to this list.

Let’s Learn together and grow together.

Satpal

Recent Posts

How to Switch PHP Versions in XAMPP Easily: Managing Multiple PHP Versions on Ubuntu

Today we are going to learn about managing multiple PHP versions on ubuntu with xampp.…

1 year ago

How to Use Coding to Improve Your Website’s SEO Ranking?

Let's understand about how to use coding to improve your website's SEO. In today’s computerized…

1 year ago

Most Important Linux Commands for Web Developers

Let's understand the most important linux commands for web developers. Linux, as an open-source and…

1 year ago

Top 75+ Laravel Interview Questions Asked by Top MNCs

Today we are going to discuss top 75+ Laravel interview questions asked by top MNCs.Laravel,…

1 year ago

Mailtrap Integration for Email Testing with Laravel 10

Today we will discuss about the Mailtrap integration with laravel 10 .Sending and receiving emails…

1 year ago

Firebase Cloud Messaging (FCM) with Ionic 6: Push Notifications

Today we are going to integrate FCM (Firebase Cloud Messaging) push notifications with ionic application.Firebase…

1 year ago