I am developing a web site in which i want the number to be formatted in the given requirement that is as below:
- If I press “1” it should say “1”.
- If I press “12” it should say “12”.
- If I press “123” it should say “1.23”.
- If I press “1234” it should say “12.34”.
- This sequence should also work when I press backspace.
I have developed it on my own that is as below:
function Maskme(obj, evt) {
var event = (window.event) ? window.event : evt;
var str = document.getElementById("txtamt");
if (event.keyCode != 8 && event.keyCode != 13) {
if (str.value.length == 3 && str.value.indexOf(".") == -1) {
var val = parseFloat(str.value);
var val1 = (val / 100).toFixed(2);
str.value = val1;
}
else if (str.value.length > 3) {
var val = parseFloat(str.value) * 1000;
var val1 = (val / 100).toFixed(2);
str.value = val1;
}
else {
str.value = str.value;
}
}
else {
if (event.keyCode != 13) {
var str1 = parseFloat(str.value) / 10;
if (str1 != 0 && !isNaN(str1))
str.value = (str1).toFixed(2);
else
str.value = "";
}
}
}
But I am having problem that is:
- If I rapidly press “123” it says “12.30” or “12.3” instead of “1.23”
- Backspace is also not working after I reach back to 1.23
- maximum 7 digits are allowed to enter in the text field
If there any ready made plugin available or anyone has already developed this kind of plugin then please inform me I will appreciate it a lot.
I changed it to replace the dot first and then the calculate is pretty easy:
DEMO: http://jsfiddle.net/ceJcn/7/