Skip to content
Fix Code Error

HTML text input allow only numeric input

March 13, 2021 by Code Error
Posted By: Jangwenyi

Is there a quick way to set an HTML text input (<input type=text />) to only allow numeric keystrokes (plus ‘.’)?

Solution

Note: This is an updated answer. Comments below refer to an old version which messed around with keycodes.

JavaScript

Try it yourself on JSFiddle.

You can filter the input values of a text <input> with the following setInputFilter function (supports Copy+Paste, Drag+Drop, keyboard shortcuts, context menu operations, non-typeable keys, the caret position, different keyboard layouts, and all browsers since IE 9):

// Restricts input for the given textbox to the given inputFilter function.
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 = "";
      }
    });
  });
}

You can now use the setInputFilter function to install an input filter:

setInputFilter(document.getElementById("myTextBox"), function(value) {
  return /^d*.?d*$/.test(value); // Allow digits and '.' only, using a RegExp
});

See the JSFiddle demo for more input filter examples. Also note that you still must do server side validation!

TypeScript

Here is a TypeScript version of this.

function setInputFilter(textbox: Element, inputFilter: (value: string) => boolean): void {
    ["input", "keydown", "keyup", "mousedown", "mouseup", "select", "contextmenu", "drop"].forEach(function(event) {
        textbox.addEventListener(event, function(this: (HTMLInputElement | HTMLTextAreaElement) & {oldValue: string; oldSelectionStart: number | null, oldSelectionEnd: number | null}) {
            if (inputFilter(this.value)) {
                this.oldValue = this.value;
                this.oldSelectionStart = this.selectionStart;
                this.oldSelectionEnd = this.selectionEnd;
            } else if (Object.prototype.hasOwnProperty.call(this, 'oldValue')) {
                this.value = this.oldValue;
                if (this.oldSelectionStart !== null &&
                    this.oldSelectionEnd !== null) {
                    this.setSelectionRange(this.oldSelectionStart, this.oldSelectionEnd);
                }
            } else {
                this.value = "";
            }
        });
    });
}

jQuery

There is also a jQuery version of this. See this answer.

HTML 5

HTML 5 has a native solution with <input type="number"> (see the specification), but note that browser support varies:

  • Most browsers will only validate the input when submitting the form, and not when typing.
  • Most mobile browsers don’t support the step, min and max attributes.
  • Chrome (version 71.0.3578.98) still allows the user to enter the characters e and E into the field. Also see this question.
  • Firefox (version 64.0) and Edge (EdgeHTML version 17.17134) still allow the user to enter any text into the field.

Try it yourself on w3schools.com.

Answered By: in.spite

Related Articles

  • Is CSS Turing complete?
  • How to allow only numeric (0-9) in HTML inputbox…
  • React Multi-level push menu SCSS Back button not working
  • Having trouble with my nav bar/header, It used to…
  • Jetpack Compose and Hilt Conflict
  • How to use html template with vue.js
  • How do I include certain conditions in SQL Count
  • Could not resolve placeholder in string value
  • How to filter a RecyclerView with a SearchView
  • Multiline editing in Visual Studio Code
  • Set keyboard caret position in html textbox
  • sidebar background is not going full to the bottom
  • Dragstart not getting invoked after reordering the elements
  • Gradle error: Execution failed for task…
  • What does this symbol mean in JavaScript?
  • Can't find keyplane that supports type 4 for…
  • What is your most productive shortcut with Vim?
  • "accept" drop option does not work in aurelia-interactjs
  • Drag and drop events for image file upload not…
  • data.table vs dplyr: can one do something well the…
  • What's the difference between KeyDown and KeyPress in .NET?
  • Scrollable Menu with Bootstrap - Menu expanding its…
  • Re-arrange position in a table maitaining order
  • jQuery: what is the best way to restrict…
  • Typeerror: n is undefined in underscore.min.js
  • Octave using 'for' statement to show two animations…
  • Is there a better way to solve this using a dictionary?
  • What is the copy-and-swap idiom?
  • Multiple context menu in a single qTableView pyqt5
  • Prevent menu close on multi select…
  • An Authentication object was not found in the…
  • org.gradle.api.tasks.TaskExecutionException:…
  • Changing cursor for draggable not working in chrome…
  • Is it possible to apply CSS to half of a character?
  • Vue.js: Including same instance of component…
  • How to display the text cursor/caret when a textbox…
  • Undefined reference to 'vtable for ✘✘✘'
  • Polymer drag-drop event object property contains…
  • How to simulate the backspace key being pressed in…
  • How to generate keyboard events?
  • How to use PrimeFaces p:fileUpload? Listener method…
  • Add space between elements
  • How to make HTML input tag only accept numerical values?
  • How do I keep only the first map and when the game…
  • Show scroll update when scrolling down page
  • How do I merge two dictionaries in a single…
  • org.springframework.beans.factory.NoSuchBeanDefiniti…
  • Spring data jpa- No bean named…
  • d3.js - dragmove circle with v6 not work as expected
  • Hide one dropdown in side menu when another opens
  • jQuery.on() Delegation: Slightly complex selector…
  • Flutter - Cubit - loaded state - managing…
  • Drop-down menu that opens up/upward with pure css
  • Active tab issue on page load HTML
  • How to keep disappearing Flutter Bottom Navigation…
  • How to get the vaadin-context-menu demo to work?
  • Solid navbar on scroll js issue
  • Android Linear Layout Parameters
  • How to Update Database from Assets Folder in App
  • Maven2: Missing artifact but jars are in place
  • Conflicting @Dragenter @Dragleave / v-show Events…
  • Autowiring fails: Not an managed Type
  • AppCompat v7 r21 returning error in values.xml?
  • Database development mistakes made by application developers
  • How to loop in Vue.js?
  • Programmatically Hide/Show Android Soft Keyboard
  • Greyscale Background Css Images
  • Start redis-server with config file
  • JavaScript gives NaN error on the page but variable…
  • creating triggers for After Insert, After Update and…
  • How to implement HorizontalScrollView like Gallery?
  • How to add "active" class to wp_nav_menu() current…
  • How does PHP 'foreach' actually work?
  • Polymer - How to data-bind paper-dropdown menu…
  • python 3.2 UnicodeEncodeError: 'charmap' codec can't…
  • How to show title in hover - css / jquery
  • How can I add class active if the element click on…
  • Is this request generated by EF Core buggy or is it my code?
  • Tomcat 7 "SEVERE: A child container failed during start"
  • How do you close/hide the Android soft keyboard using Java?
  • How Spring Security Filter Chain works
  • Create code first, many to many, with additional…
  • Properly closing views in Marionette
  • How to make Twitter Bootstrap menu dropdown on hover…
  • Polymer 2.0 - Trying to implement HTML5 drag and drop
  • Ember.js + HTML5 drag and drop shopping cart demo
  • How to vertically align an image inside a div
  • How to integrate custom context menus in Mithril
  • JavaScript hashmap equivalent
  • JavaScript get clipboard data on paste event (Cross browser)
  • Material Design Lite + Polymer not working together…
  • Trying to keep dropdown menus flush to the edge of…
  • How to set `border-radius` of `paper-listbox` inside…
  • Validation failed for one or more entities. See…
  • How can I find the product GUID of an installed MSI setup?
  • Polymer paper-dropdown-menu not rendered correctly…
  • How do I use InputFilter to limit characters in an…
  • Entity Framework LINQ complex query - combine…
  • recyclerview opens wrong item after filtering list…
  • Bootstrap: Position of dropdown menu relative to navbar item

Disclaimer: This content is shared under creative common license cc-by-sa 3.0. It is generated from StackExchange Website Network.

Post navigation

Previous Post:

How can I get the ID of an element using jQuery?

Next Post:

How do I determine whether an array contains a particular value in Java?

Leave a Reply Cancel reply

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

.net ajax android angular arrays aurelia backbone.js bash c++ css dataframe ember-data ember.js excel git html ios java javascript jquery json laravel linux list mysql next.js node.js pandas php polymer polymer-1.0 python python-3.x r reactjs regex sql sql-server string svelte typescript vue-component vue.js vuejs2 vuetify.js

  • you shouldn’t need to use z-index
  • No column in target database, but getting “The schema update is terminating because data loss might occur”
  • Angular – expected call-signature: ‘changePassword’ to have a typedeftslint(typedef)
  • trying to implement NativeAdFactory imports deprecated method by default in flutter java project
  • What should I use to get an attribute out of my foreign table in Laravel?
© 2022 Fix Code Error