document.getElementById('value').addEventListener('keydown', function(e) {
var key = e.keyCode ? e.keyCode : e.which;
/*lenght of value to use with index to know how many numbers after.*/
var len = $('#value').val().length;
var index = $('#value').val().indexOf('.');
if (!( [8, 9, 13, 27, 46, 110, 190].indexOf(key) !== -1 ||
(key == 65 && ( e.ctrlKey || e.metaKey ) ) ||
(key >= 35 && key <= 40) ||
(key >= 48 && key <= 57 && !(e.shiftKey || e.altKey)) ||
(key >= 96 && key <= 105)
)){
e.preventDefault();
}
/*if theres a . count how many and if reachs 2 digits after . it blocks*/
if (index > 0) {
var CharAfterdot = (len + 1) - index;
if (CharAfterdot > 3) {
/*permits the backsapce to remove :D could be improved*/
if (!(key == 8))
{
e.preventDefault();
}
/*blocks if you try to add a new . */
}else if ( key == 110) {
e.preventDefault();
}
/*if you try to add a . and theres no digit yet it adds a 0.*/
} else if( key == 110&& len==0){
e.preventDefault();
$('#value').val('0.');
}
});
задан kmario23 18 January 2018 в 01:54
поделиться