0

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: enter image description here

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?

knot22
  • 2,648
  • 5
  • 31
  • 51
  • It seems you are using "this" in wrong context. It's not referring to the "input field", so try "var v = $(e.target).val()" or use actual identifier Eg: $("#inputName") – Murali Nepalli Nov 11 '19 at 00:32
  • 1
    https://jsfiddle.net/5p4owdLv/ – Murali Nepalli Nov 11 '19 at 00:50
  • I just discovered that in Firefox keyCode 173 needs to be added to the array for `oneNegativeSignOnly`. See https://stackoverflow.com/questions/1898129/javascript-subtract-keycode. – knot22 Nov 11 '19 at 00:58

1 Answers1

1
function oneDecimalPointOnly(e) {       
    limitCharacterToOne(e, '.', [190, 110]) ;
 }

function oneNegativeSignOnly(e) {
   limitCharacterToOne(e, '-', [189, 109]);
}


function limitCharacterToOne(e, character, keyCodes) {
    var v = $(e.target).val();
    if (v.indexOf(character) > -1 && $.inArray(e.keyCode, keyCodes) > -1) { 
       e.preventDefault();
    }   
}
Murali Nepalli
  • 1,588
  • 8
  • 17