Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 406
Alexander Kim Avatar asked Oct 24 '25 19:10

Alexander Kim


1 Answers

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/

like image 161
Ivan Sivak Avatar answered Oct 26 '25 07:10

Ivan Sivak



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!