简体   繁体   中英

How to make input field to accept only numbers

I have a input field which is of type number so that it can accept numbers only -I am using regex to restrict user to enter special characters -it is working fine on system,but on small device as in my mobile phone the keypad type is only number,but when i am clicking on - it is taking that which i don't want

What i have done

 $('#test').on('keypress', function(event) { var regex = new RegExp("^[0-9]+$"); var key = String.fromCharCode(!event.charCode ? event.which : event.charCode); if (!regex.test(key)) { event.preventDefault(); return false; } }); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.2/css/bootstrap.min.css"> <input type="number" class="form-control" id="test"> 

It is showing up like this on mobile

这个

-i have tried regex to restrict it but not working on phone

Edit I am almost close, i am trying below code,but it is taking minus - first time when i press not the next time,like if i enter 55 then i press - it is not taking it but when i press - before any number it is taking

 (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); } }); }; }(jQuery)); $("#uintTextBox").inputFilter(function(value) { return ^\\d + [.] ? \\d + $.test(value); }); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <input id="uintTextBox" type="tel"> 

Use this regular expression to not allow - character in the beginning with the <input type="tel"> :

/^\d*[.]?\d*$/

Please see working fiddle: https://jsfiddle.net/uhkv65yj/

 /* Function allows only numbers and decimal */
$(document).on('keypress','#test',function(eve) {
    if ((  eve.which != 45 ||eve.which != 46 || $(this).val().indexOf('.') != -1 ) 
         && ( eve.which <  48 || eve.which > 57 ) 
         || ( $(this).val().indexOf('.') == 0) 
       )
       {
            eve.preventDefault();
       }
 })

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM