Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery only allow input float number

Tags:

i'm making some input mask that allows only float number. But current problem is I can't check if multiple dots entered. Can you check those dots and prevent it for me?

Live Code: http://jsfiddle.net/thisizmonster/VRa6n/

$('.number').keypress(function(event) {     if (event.which != 46 && (event.which < 47 || event.which > 59))     {         event.preventDefault();         if ((event.which == 46) && ($(this).indexOf('.') != -1)) {             event.preventDefault();         }     } }); 
like image 421
Gereltod Avatar asked Jun 21 '11 07:06

Gereltod


People also ask

How to restrict numeric input in javascript?

1. Using <input type="number"> The standard solution to restrict a user to enter only numeric values is to use <input> elements of type number. It has built-in validation to reject non-numerical values.

How to allow only decimal values in textbox jQuery?

jQuery: Code to allow numbers and decimal values in the textbox. Here in our 2nd textbox, we added allow_decimal class and on its event will allow a user to enter decimal values.

How to validate decimal value in jQuery?

jQuery validator also supports decimal validation using range method. factor: { required: true, range:[0.08,20.09] }, Read more here and demo here.


1 Answers

You can check for the period in the same statement.

Also, you need to use the val method to get the value of the element.

Also, you want to check for the interval 48 to 57, not 47 to 59, otherwise you will also allow /, : and ;.

$('.number').keypress(function(event) {   if ((event.which != 46 || $(this).val().indexOf('.') != -1) && (event.which < 48 || event.which > 57)) {     event.preventDefault();   } }); 
like image 115
Guffa Avatar answered Sep 20 '22 18:09

Guffa