Alexander Kim
Alexander Kim

Reputation: 18382

Allow only numbers and one dot in input

Using the following code with jQuery:

$('#from-amount').keypress(function(event) {
    if ((event.which != 46 || $(this).val().indexOf('.') != -1) && (event.which < 48 || event.which > 57)) {
        event.preventDefault();
    }
});

It does work, but i can use . at the start and paste (with the mouse and keyboard CMD+V) any string. How can i prevent . at the start and disable paste with keyboard and mouse?

Upvotes: 4

Views: 12789

Answers (1)

Ivan Sivak
Ivan Sivak

Reputation: 7488

Try this

$('#from-amount').keypress(function(event) {
    if (((event.which != 46 || (event.which == 46 && $(this).val() == '')) ||
            $(this).val().indexOf('.') != -1) && (event.which < 48 || event.which > 57)) {
        event.preventDefault();
    }
}).on('paste', function(event) {
    event.preventDefault();
});

https://jsfiddle.net/4rsv960t/1/

Upvotes: 12

Related Questions