I'm using JQuery Masked input plugin.
$("#percent").mask("99.99?9");
This allows numbers like 10.999, 10.99, 01.999, 01.99
What I want to achieve is that I don't want user to type 01.99
. Instead if user types 1.99
I want 0
before 1
to be automatically added. This is how I started but don't know how to continue:
//assume i typed in field 11.99
$(document).on('keyup', '#percent', function(evt) {
var input = $(this).val();
alert(input); // 11.99_
if(evt.which == '190' || evt.which == '110') {
//if dot is clicked
alert(parseInt(input)); // 11
}
});
Note that alert input prints 11.99_
with underscore at the end since third value is optional and I didnt input it.
Now this value is perfectly normal but if user entered 1.99
, would be unable since it would automatically move 9
towards 1
to fill it up with 2
digits, so it would return as 19.9
and this is invalid since there must be 2
decimals as defined above. So in my if statement I want to be able to detect if whatever was entered is less than 10
, if it's less than 10
in decimal points then add 0
at the beginning.
Ok I found a fix for underscore _
:
$("#percent").mask("99.99?9", {placeholder: ""})
but still does not fix other issue with entering 1.99
being 19.9
You can intercept keydown to do this, but you'll need some way to refresh plugin state.
The following code will do work:
$("#percent").bind({
keydown: function(e) {
// custom handler for dot
var userInput = parseFloat($("#percent").val());
if(e.which == '190' || e.which == '110') {
// if entered number is integer and less than 10
if(userInput % 1 === 0 && userInput < 10) {
// prevent default mask input handlers from calling
e.preventDefault();
e.stopImmediatePropagation();
// update value
$("#percent").val('0'+userInput+'.');
// simulate paste event to refresh mask input plugin state
$("#percent").trigger('paste').trigger('input');
}
}
}
}).mask("99.99?9", {placeholder: ""});
Working JSFiddle here