So I am trying to take US SSN as input and trying to mask it by automatically inserting dashes, not allowing more than 9 digits, etc.
Please see the Fiddle.
My problems with the code is:
I have disabled the arrow keys, that is because if someone goes back using arrow keys and presses backspace ( to do an edit to a specific number), my code breaks, and it inserts extra dashes, which is unacceptable.
My code looks like:
$('#ssn').on("keyup change paste mouseup", function(evt) {
setTimeout(function() {
var $ssn = $('#ssn');
var $length = $ssn.val().length;
var $value = $ssn.val();
$ssn.val(formatSSN($value));
}, 10);
});
// Start of section that prevents arrow keys
$('#ssn').on("click focus", function(evt) {
var value = $(this).val();
$(this).val('').val(value);
});
$('#ssn').on("keydown", function(evt) {
var key = evt.keyCode;
if (key >= 37 && key <= 40) {
$(this).focus();
var value = $(this).val();
$(this).val(' ').val(value);
evt.stopPropagation();
return false;
}
});
// End of section that prevents arrow keys
function formatSSN(inputSSN) {
var dashPositions = [3, 6];
var inputLength = inputSSN.length;
var output = inputSSN;
for (i in dashPositions) {
if (dashPositions[i] < inputLength) {
if (output[dashPositions[i]] !== '-') {
var firstPart = output.substring(0, dashPositions[i]) + '-';
var secondPart = output.substring(dashPositions[i]);
output = firstPart + secondPart;
}
}
}
if (output.length > 11) {
output = output.substring(0, 11);
}
return output;
}
My question is:
Is there any way I can enable the arrow keys, and still preserve the positions of the dashes? (prevent extra/misplaced dashes) ?
Thanks.