Cash
by rippo
HTML
<input type="number" id="cash" class="cash" step="any" autofocus="autofocus" autocomplete="off" />
CSS
.cash {
background: #93FF75;
color: #555;
border: 4px solid #555;
font-size: 24px;
padding: 10px;
text-align: right;
outline: none;
}
input[type=number]::-webkit-inner-spin-button, input[type=number]::-webkit-outer-spin-button {
-webkit-appearance: none;
margin: 0;
}
JavaScript
jQuery('.cash').keydown(function (e) {
if ($.inArray(e.keyCode, [46, 8, 9, 27, 13]) !== -1) {
return;
}
// Ensure that it is a number and stop the keypress
if (e.keyCode < 48 || e.keyCode > 57) {
e.preventDefault();
}
});
jQuery('.cash').keypress(function (e) {
var value = String.fromCharCode(e.keyCode);
if (this.value.length > 0) {
value = this.value + String.fromCharCode(e.keyCode);
}
value = value.replace('0.0', '').replace('0.', '').replace('.', '');
var amount = parseFloat(value);
console.log(value);
if (amount >= 100) {
this.value = value.insert(value.length - 2, ".");
e.preventDefault();
return;
}
if (amount >= 10) {
this.value = '0.' + amount;
e.preventDefault();
return;
}
this.value = '0.0' + amount;
e.preventDefault();
});
String.prototype.insert = function (index, string) {
if (index > 0) return this.substring(0, index) + string + this.substring(index, this.length);
else return string + this;
};