lazy rabbit lazy rabbit - 3 months ago 15
jQuery Question

Allow only floating values to be inputted, maximum value being 100.00

There's a HTML input text field, say for price, for which it is required that it's maximum price could be 100.00, minimum could be 0.00 .

Jquery code to allow used this range is as follows:

$('#price').keypress(function(event) {
if(event.which == 8 || event.which == 0){
return true;
}
if(event.which < 46 || event.which > 59) {
return false;
//event.preventDefault();
} // prevent if not number/dot

if(event.which == 46 && $(this).val().indexOf('.') != -1) {
return false;
//event.preventDefault();
} // prevent if already dot
});


But this allows users to put in
12345
or
1235
or
123.5
etc.
Corresponding HTML for the text box is :

<input type="text" name ="" value="" id="price" maxlength="5" min="0.01" step="0.01">


If
type="text"
is changed to
type="number"
, the applied Jquery doesn't work on it.

How can we allow user to input just the float numbers from 0.00 to 100.00 and ONLY up to 2 decimal places. eg : 4.32, 9.99, 99.99 etc.

Answer

You can use jquery mask plugin

html

<input type="text" id="price">

js

$('#price').mask('Z00.00', {translation:  {'Z': {pattern: /[1]/, optional: true}}});

fiddle demo