First, write a trimming function
function trimDP(x, dp) {
if (dp === 0)
return Math.floor(+x).toString();
dp = Math.pow(10, dp || 2);
return (Math.floor((+x) * dp) / dp).toString();
}
// ex.
trimDP("1.2345"); // "1.23"
Next, set up this trimming function to be applied on keypress and onchange to your <input>
e.g. by giving them the class token dp2
<input type="text" value="0" class="dp2" />
(function () { // do this after nodes loaded
var nodes = document.querySelectorAll('.dp2'), i;
function press(e) {
var s = String.fromCharCode(e.keyCode);
if (s === '.')
if (this.value.indexOf('.') === -1)
return; // permit typing `.`
this.value = trimDP(this.value + s);
e.preventDefault();
};
function change() {
this.value = trimDP(this.value);
}
for (i = 0; i < nodes.length; ++i) {
nodes[i].addEventListener('keypress', press);
nodes[i].addEventListener('change', change);
}
}());
You may also want to prevent non-numeric keys