Skip to content
Fix Code Error

How to allow only numeric (0-9) in HTML inputbox using jQuery?

March 13, 2021 by Code Error
Posted By: Anonymous

I am creating a web page where I have an input text field in which I want to allow only numeric characters like (0,1,2,3,4,5…9) 0-9.

How can I do this using jQuery?

Solution

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

jQuery

Try it yourself on JSFiddle.

There is no native jQuery implementation for this, but you can filter the input values of a text <input> with the following inputFilter plugin (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 set of matched elements to the given inputFilter function.
(function($) {
  $.fn.inputFilter = function(inputFilter) {
    return this.on("input keydown keyup mousedown mouseup select contextmenu drop", 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 = "";
      }
    });
  };
}(jQuery));

You can now use the inputFilter plugin to install an input filter:

$(document).ready(function() {
  $("#myTextBox").inputFilter(function(value) {
    return /^d*$/.test(value);    // Allow digits only, using a RegExp
  });
});

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

Pure JavaScript (without jQuery)

jQuery isn’t actually needed for this, you can do the same thing with pure JavaScript as well. 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: Anonymous

Related Articles

  • Jetpack Compose and Hilt Conflict
  • How can i display data from xml api in flutter?
  • React Multi-level push menu SCSS Back button not working
  • Having trouble with my nav bar/header, It used to…
  • HTML text input allow only numeric input
  • How to solve Internal Server Error in Next.Js?
  • Aurelia UX showcase app fails to load
  • How do I include certain conditions in SQL Count
  • Could not resolve placeholder in string value
  • How to use html template with vue.js
  • org.gradle.api.tasks.TaskExecutionException:…
  • Dragstart not getting invoked after reordering the elements
  • Multiline editing in Visual Studio Code
  • How to filter a RecyclerView with a SearchView
  • Is it possible to apply CSS to half of a character?
  • sidebar background is not going full to the bottom
  • Gradle error: Execution failed for task…
  • Specifying java version in maven - differences…
  • jQuery Mobile: document ready vs. page events
  • Can't find keyplane that supports type 4 for…
  • "accept" drop option does not work in aurelia-interactjs
  • Set keyboard caret position in html textbox
  • Aurelia bundling issue with virtual directory
  • Error: undefined Unable to resolve module
  • How to change the color of vaadin-select-text-field…
  • Drag and drop events for image file upload not…
  • Tomcat 7 "SEVERE: A child container failed during start"
  • What's the difference between KeyDown and KeyPress in .NET?
  • org.springframework.beans.factory.NoSuchBeanDefiniti…
  • An Authentication object was not found in the…
  • How Spring Security Filter Chain works
  • Spring Boot - Cannot determine embedded database…
  • Scrollable Menu with Bootstrap - Menu expanding its…
  • Include resource directory into Quarkus target output
  • data.table vs dplyr: can one do something well the…
  • Spring data jpa- No bean named…
  • What are the undocumented features and limitations…
  • Re-arrange position in a table maitaining order
  • Is CSS Turing complete?
  • Error creating bean with name
  • What is the copy-and-swap idiom?
  • jQuery: what is the best way to restrict…
  • Launching Spring application Address already in use
  • How to use PrimeFaces p:fileUpload? Listener method…
  • Fastest way to iterate over all the chars in a String
  • Octave using 'for' statement to show two animations…
  • Flutter - Cubit - loaded state - managing…
  • Multipart File Upload Using Spring Rest Template +…
  • Multiple context menu in a single qTableView pyqt5
  • Prevent menu close on multi select…
  • Is there a better way to solve this using a dictionary?
  • Changing cursor for draggable not working in chrome…
  • Adobe XD to responsive html
  • What is your most productive shortcut with Vim?
  • Vue.js: Including same instance of component…
  • Invoke native date picker from web-app on iOS/Android
  • Comparison between Corona, Phonegap, Titanium
  • Polymer drag-drop event object property contains…
  • coercing to Unicode: need string or buffer, NoneType…
  • Show scroll update when scrolling down page
  • Failed to execute goal…
  • Could not calculate build plan: Plugin…
  • How to make HTML input tag only accept numerical values?
  • My Application Could not open ServletContext resource
  • Undefined reference to 'vtable for ✘✘✘'
  • Spring schemaLocation fails when there is no…
  • How to keep disappearing Flutter Bottom Navigation…
  • How to get the vaadin-context-menu demo to work?
  • Autowiring fails: Not an managed Type
  • How to simulate the backspace key being pressed in…
  • d3.js - dragmove circle with v6 not work as expected
  • Why am I getting a "401 Unauthorized" error in Maven?
  • jQuery.on() Delegation: Slightly complex selector…
  • Maven2: Missing artifact but jars are in place
  • VueJS - Dynamic repeating component
  • Polymer 1.0 'array-style' path accessors,…
  • How do I merge two dictionaries in a single…
  • Android Linear Layout Parameters
  • python 3.2 UnicodeEncodeError: 'charmap' codec can't…
  • Solid navbar on scroll js issue
  • How do I use InputFilter to limit characters in an…
  • Add space between elements
  • Hide one dropdown in side menu when another opens
  • How to add "active" class to wp_nav_menu() current…
  • Building executable jar with maven?
  • Django - update inline formset not updating
  • Programmatically Hide/Show Android Soft Keyboard
  • Drop-down menu that opens up/upward with pure css
  • Java.lang.NoClassDefFoundError:…
  • Validation failed for one or more entities. See…
  • How to Update Database from Assets Folder in App
  • How to loop in Vue.js?
  • Conflicting @Dragenter @Dragleave / v-show Events…
  • How to show title in hover - css / jquery
  • Greyscale Background Css Images
  • How to loop through a column to copy all matching…
  • How does PHP 'foreach' actually work?
  • How to implement HorizontalScrollView like Gallery?
  • Polymer - How to data-bind paper-dropdown menu…
  • Typeerror: n is undefined in underscore.min.js

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 do I check what version of Python is running my script?

Next Post:

Git merge master into feature branch

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