I have a couple of methods that look a lot the same and seem like good candidates for refactoring:
// if there is already a decimal in the value and user presses period on keyboard (190) or decimal on keypad (110) then prevent entry of that period or decimal
function oneDecimalPointOnly(e) {
var v = $(this).val();
if (v.indexOf('.') > -1 && $.inArray(e.keyCode, [190, 110]) > -1) {
e.preventDefault();
}
}
// if there is already a negative sign in the value and user presses minus on keyboard (189) or subtract on keypad (109) then prevent entry of that minus or subtract
function oneNegativeSignOnly(e) {
var v = $(this).val();
if (v.indexOf('-') > -1 && $.inArray(e.keyCode, [189, 109]) > -1) {
e.preventDefault();
}
}
They are bound as follows:
$(':text').on('keydown', oneDecimalPointOnly);
$(':text').on('keydown', oneNegativeSignOnly);
As written, they accomplish the task correctly, preventing the entry of multiple decimals or negatives in text boxes.
For refactoring, here is what I've tried:
function oneDecimalPointOnly(e) {
limitCharacterToOne(e, '.', [190, 110]);
}
function oneNegativeSignOnly(e) {
limitCharacterToOne(e, '-', [189, 109]);
}
// if character is already in the value and user presses a key in the keyCodes array then prevent entry of that character
function limitCharacterToOne(e, character, keyCodes) {
var v = $(this).val();
if (v.indexOf(character) > -1 && $.inArray(e.keyCode, keyCodes) > -1) {
e.preventDefault();
}
}
However, the console is showing this error:
And the refactored version does not prevent the entry of multiple decimals or negatives in text boxes.
What modifications are needed in the refactored version so it prevents the entry of multiple decimals or negatives?