l2aelba
l2aelba

Reputation: 22167

Why this function for input with number only doesnt work actually with input type:number?

$('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?

Upvotes: 1

Views: 76

Answers (1)

Nikhil Talreja
Nikhil Talreja

Reputation: 2774

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;
    }
});

Upvotes: 1

Related Questions