Table of Contents
1) max and min
2) oninput event
3) keydown
4) With keypress, keydown and oninput
5) input parttern
Home Web Front-end JS Tutorial What method should be used to limit the number of input digits in js?

What method should be used to limit the number of input digits in js?

Jun 29, 2017 am 09:35 AM
input type

When we use an input input box of type number, we may need to limit the number of input digits. At this time, we usually think of maxlength, but maxlength is not supported when it is of type number. Here are some solutions to this problem problem method.

1) max and min

max and min are supported by the number input box, so if we want to limit the input of 11-digit mobile phone numbers, we can use the following code

<input type="number" max="99999999999" />
Copy after login

This will not limit user input, but will prompt the user when submitting.

[Example]

2) oninput event

Slice the excess digits and delete them

1 myInput.oninput = function () {2     if (this.value.length > 4) {3         this.value = this.value.slice(0,4); 
4     }5 }
Copy after login

But This is still slightly different from the logic of maxlength, that is, when we move the cursor between the previously entered numbers, we will find that entering another number will cause the last number to be deleted.

[Example]

3) keydown

The keydown event can help us determine the number of digits in the value in the current input after pressing the number. If it exceeds the number of digits Just return false, so no matter where the cursor is, no new numbers will be entered.

<input type="number" onKeyDown="if(this.value.length==2) return false;" />
Copy after login

But this will cause the delete key (or all keys) to be invalid when 2 numbers are met. ╮(╯﹏╰)╭It’s really embarrassing

[Example]

4) With keypress, keydown and oninput

 1 <input name="myInput_DRS" onkeypress="return isNumeric(event)" 
 onkeydown="return isMoreThan(event)" oninput="maxLengthCheck(this)" 
 type="number" placeholder="Type..." min="1" max="999" /> 2  3 <script> 4   
 function maxLengthCheck(object) { 5     
 if (object.value.length > object.max.length) 6       
 object.value = object.value.slice(0, object.max.length) 7   }   
 function isNumeric(evt) {10     var theEvent = evt || window.event;11     
 var key = theEvent.keyCode || theEvent.which;12     key = String.fromCharCode(key);13    
 var regex = /[0-9]|\./;14     if (!regex.test(key)) {15       theEvent.returnValue = false;16       
 if (theEvent.preventDefault) theEvent.preventDefault();17     }18   }19 20   function isMoreThan(evt) {21     
 var theEvent = evt || window.event;22     var target = theEvent.target;23     var keyID = event.keyCode;24     
 var isDelete = false;25     switch (keyID) {26       case 8:27           isDelete = true;28         
 // alert("backspace");29         break;30       case 46:31           isDelete = true;32         
 // alert("delete");33         break;34       default:35         break;36     }37 38     
 if (!isDelete && target.value.length == target.max.length) {39       return false;40     
 } 
 } 
 </script>
Copy after login

[Example]

5) input parttern

<input type="text" pattern="\d*" maxlength="2">
Copy after login

But the compatibility is not good, Internet Explorer 10, Firefox, Opera and Chrome support the pattern attribute.

Note: Safari or Internet Explorer 9 and earlier versions do not support the pattern attribute of the tag.

6) input[type=tel]

On mobile devices, input[type=tel] supports maxlength , and can only be entered using the numeric keyboard.

The above is the detailed content of What method should be used to limit the number of input digits in js?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Solve Ubuntu mounting mobile hard disk error: unknown file system type exfat Solve Ubuntu mounting mobile hard disk error: unknown file system type exfat Jan 05, 2024 pm 01:18 PM

An error occurs when ubuntu mounts a mobile hard disk: mount: unknownfilesystemtype'exfat'. The processing method is as follows: Ubuntu13.10 or install exfat-fuse: sudoapt-getinstallexfat-fuseUbuntu13.04 or below sudoapt-add-repositoryppa:relan/exfatsudoapt-getupdatesudoapt-getinstallfuse- exfatCentOS Linux mount exfat format USB disk error solution to load extfa in CentOS

What are the uses of the Type keyword in Go? What are the uses of the Type keyword in Go? Sep 06, 2023 am 09:58 AM

The usage of the Type keyword in Go includes defining new type aliases or creating new structure types. Detailed introduction: 1. Type alias. Use the "type" keyword to create an alias for an existing type. This alias does not create a new type, but only provides a new name for the existing type. Type aliases can improve code. The readability of the code makes the code clearer; 2. Structure type. Use the "type" keyword to create a new structure type. The structure is a composite type that can be used to define custom types containing multiple fields. etc.

How to encapsulate input components and unified form data in vue3 How to encapsulate input components and unified form data in vue3 May 12, 2023 pm 03:58 PM

Preparation Use vuecreateexample to create a project. The parameters are roughly as follows: use native input. Native input is mainly value and change. The data needs to be synchronized when changing. App.tsx is as follows: import{ref}from'vue';exportdefault{setup(){//username is the data constusername=ref('Zhang San');//When the input box changes, synchronize the data constonInput=;return( )=>({

How to implement laravel input hidden field How to implement laravel input hidden field Dec 12, 2022 am 10:07 AM

How to implement the laravel input hidden field: 1. Find and open the Blade template file; 2. Use the method_field method in the Blade template to create a hidden field. The creation syntax is "{{ method_field('DELETE') }}".

What to do if there is no cursor when clicking on the input box What to do if there is no cursor when clicking on the input box Nov 24, 2023 am 09:44 AM

Solutions for clicking the input box without a cursor: 1. Confirm the focus of the input box; 2. Clear the browser cache; 3. Update the browser; 4. Use JavaScript; 5. Check the hardware device; 6. Check the input box properties; 7. Debug JavaScript code; 8. Check other elements of the page; 9. Consider browser compatibility.

Detailed explanation of input box binding events in Vue documents Detailed explanation of input box binding events in Vue documents Jun 21, 2023 am 08:12 AM

Vue.js is a lightweight JavaScript framework that is easy to use, efficient and flexible. It is one of the most popular front-end frameworks currently. In Vue.js, input box binding events are a very common requirement. This article will introduce the input box binding events in the Vue document in detail. 1. Basic concepts In Vue.js, the input box binding event refers to binding the value of the input box to the data object of the Vue instance, thereby achieving two-way binding of input and response. In Vue.j

How to use the input box carriage return event and verification function in the Vue document How to use the input box carriage return event and verification function in the Vue document Jun 20, 2023 am 09:13 AM

Vue is a popular JavaScript front-end framework with a responsive data binding and component system at its core. In Vue applications, the input box is one of the most commonly used UI elements. When the user enters text, we hope to listen for the carriage return event and validate the input before submitting. This article will introduce the input box enter event and verification function usage in the Vue document. 1. The carriage return event of the input box in Vue. Monitoring the carriage return event of the input box in Vue is very simple.

Linux type command Linux type command Mar 20, 2024 pm 05:06 PM

In this guide, we will learn more about the &quot;type&quot; command in Linux. Prerequisites: To perform the steps demonstrated in this guide, you need the following components: A properly configured Linux system. See how to create a LinuxVM for testing and learning purposes. Basic understanding of the command line interface The Type command in Linux is different from other Linux-specific commands (for example: ls, chmod, shutdown, vi, grep, pwd, etc.). The &quot;type&quot; command is a built-in Bash function that is displayed as an argument. Information about the command type provided. $type In addition to Bash, other shells (Zsh, Ksh, etc.) also come with

See all articles