1
$('input').on('keyup',function(){
    this.value = this.value.replace(/[^0-9\.]/g,'');
});

From : https://stackoverflow.com/a/891816/622813

After I tested with <input type="number">

When I type something like 1234a so value is blank

But not with <input type="text"> when I type 1234a value is still 1234

Just wonder why ?

Demo : http://jsfiddle.net/PV2fQ/


Update :

<input type="tel"> this work good ... http://jsfiddle.net/PV2fQ/10/ Why?

Community
  • 1
  • 1
l2aelba
  • 21,591
  • 22
  • 102
  • 138
  • Out of curiosity , I tried the above code on all browsers , the code works fine on Mozilla Firefox , Internet Explorer 11 and Apple safari (i.e. it just removes non numeric characters) but not on Google chrome & Opera. – Sachin Gadagi Jul 04 '14 at 07:57

1 Answers1

1

If you do a console.log(this.value); before your replace statement, you will see that for non-number inputs <input type="number"> gets a blank value itself i.e this.value = '';

This seems to be the internal implementation of this input type.

An alternative: http://jsfiddle.net/PV2fQ/12/

$('input').keypress(function (e) {
    if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
        return false;
    }
});
Nikhil Talreja
  • 2,754
  • 1
  • 14
  • 20
  • what exactly would you like to happen and what type of input do you want to use? – Nikhil Talreja Jul 04 '14 at 07:46
  • Just want to use `type:number` becouse mobile keyboard will show number only... something like that – l2aelba Jul 04 '14 at 07:47
  • I believe that if type=number, the user will be shown only the number keyboard on the phone so you need not worry about them entering non-numbers on the field. Check [here](http://html5doctor.com/html5-forms-input-types/#input-number) – Nikhil Talreja Jul 04 '14 at 07:51
  • Yes but what about desktop browsers :P – l2aelba Jul 04 '14 at 07:51
  • nice.... maybe I will use that, But still wonder why its doesnt work good on type:number :D – l2aelba Jul 04 '14 at 07:55
  • 1
    @l2aelba: it does work well on number-type inputs. Too well even, in Firefox 30: type in a number plus a letter, and the whole input is deleted. For more information on the behavior of some new browsers with number-type inputs, although from a significantly different perspective, see http://stackoverflow.com/questions/24407109/new-webkits-convert-decimal-comma-to-dot-and-vice-versa-in-number-type-inputs. Just to show that there is something going on in browser world in this respect, that is not well defined by W3 standards. So, I would go with Nikhil's solution, if that works for you. – Frank Conijn - Support Ukraine Jul 05 '14 at 10:48