0

I am working on a mobile web application where I need to use a text box which is of type "Number".

<input type="number" name="Mileage" id="txtExample" onkeypress="javascript:return validateNumbers(event,'txtExample');"/>

The problem am getting is here I need to restrict the dot (.) from being entered in to text box and the javascript method I have written for this is:

function validateNumbers(evt, txtField) {            
    var charCode = (evt.which) ? evt.which : event.keyCode;
    if (charCode > 31 && (charCode < 48 || charCode > 57))
        return false;
    else if (charCode == 8)
        return true;            
    }

The charcode of . is 46 but its going in to true every time. The strange thing is in desktop website this code is working fine but when running in mobile browser (Chrome, IE) it's not working.

I need assistance guys. This approach don't work in Mobile browser. Thanks in advance.

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
adla praveen
  • 161
  • 2
  • 13
  • why not use the min attribute so you don't have this problem? – madalinivascu Oct 13 '16 at 11:36
  • Related: http://stackoverflow.com/questions/31979619/how-to-get-keycodes-from-android-mobile-device-keyboard – Turnip Oct 13 '16 at 11:37
  • 1
    You ask question about: `How to restrict dot operator('.')`. But isn't your question just `How to restrict only integer in input type number`??? If so, google it – A. Wolff Oct 13 '16 at 11:41

1 Answers1

0

Take a look at this example

$("#txtExample").on("keypress",function(evt){
    var keycode = evt.charCode || evt.keyCode;
      if (keycode  == 46) {
        return false;
      }
});
Rick Bronger
  • 330
  • 1
  • 15
  • This code is restricting the dot in the input field. Nothing more nothing less. Look at his question. How to restrict dot operator('.') in mobile browser using Javascript/ JQuery – Rick Bronger Oct 13 '16 at 11:44
  • @Rick Bronger, Yeah i used the same code but its not returning false once i run it in mobile browser. Simply, i should allow only 0 to 9 numbers to be entered by User. – adla praveen Oct 13 '16 at 11:48
  • When i press dot in text box , am unable to catch the key code its coming blank may be because if input type="number" ? its working when i give as type="text". I Want this to work in "Number type". – adla praveen Oct 13 '16 at 11:50
  • @ Rick Bronger, thanks for posting fiddle example but i know its working in desktop browser just open the same http://jsfiddle.net/8nz11auz/4/ link in mobile using any browser and just see, my concern is that. Could you please post any suggestion how i can achieve that in mobile browser. – adla praveen Oct 13 '16 at 12:44