I validate an input field by those patterns:
- only positive numbers
- only one .
- only numeric values
- only two decimals after .
- only numbers between 0 and 100
- limit input to 5 characters (0 ... 1.1 ... 10.2 ... 33.23 ... 99.99 or 100)
These validations work with my code fine. Even there is a better way to code this validation. But anyways - my issue, which I can't solve right now is - if I enter a value for example 99.99 or 100 or 23.23 and I want to change the value again by selecting / mark the entire value with my mouse for example - it will not change! If I write 2.33 and I select/mark the entire value with my mouse it will change. So it seems I'm facing a 'false' state which does not allow me to enter another digit and right now I could not find a kind of an event which detects that I select something in my input field.
I have prepared an JSFIDDLE code - where do I have my confusion?
ps: I am also aware that maybe my keypress event is overwriting the false/true states, I'm trying to solve this afterwards.
Thank you very much! Best Regards
$('#inpNumber').on('input', function() {
var inpVal = $(this).val();
if ( inpVal > 100 || inpVal < 0 || !inpVal) {
$( "#inpNumber" ).removeClass( "is-valid" );
$( "#inpNumber" ).addClass( "is-invalid" );
} else {
$( "#inpNumber" ).removeClass( "is-invalid" );
$( "#inpNumber" ).addClass( "is-valid" );
}
});
$('#inpNumber').keypress(function (event) {
var input = $(this).val();
if ((input.indexOf('.') != -1) && (input.substring(input.indexOf('.')).length > 2)) {
event.preventDefault();
return false;
}
return isNumberRegChecked(event, this);
return isNumber(event, this);
});
function isNumberRegChecked( evt, element ) {
var inpVal = $(element).val();
// ^(\d\d?(\.\d\d?)?|100(\.00?)?)$ also possible
var checkShare = /^(\d{0,2}(\.\d{0,2})?)$/.test(inpVal);
if (checkShare == false)
return false;
return true;
}
// THE SCRIPT THAT CHECKS IF THE KEY PRESSED IS A NUMERIC OR DECIMAL VALUE.
function isNumber( evt, element ) {
var charCode = (evt.which) ? evt.which : event.keyCode;
if ((charCode != 46 || $(element).val().indexOf('.') != -1) && // “.” CHECK DOT, AND ONLY ONE.
(charCode < 48 || charCode > 57))
return false;
return true;
}