How to Automatically Add Series of Hyphens to Text Field with A Preset Text While Typing?
I have a text field with a default value of "NAFID1" and a mouse up action: on blur that works to always keep the preset text in the field and to protect the preset text from deletion. In other words, if any character of the preset text is deleted, it will reset the field automatically to the preset text.
// Define your preset text
var presetText = "NAFID1";
// Get the current value of the field
var currentValue = event.target.value;
// If the field is empty or doesn't start with the preset text, add it
if(!currentValue.startsWith(presetText)) {
event.target.value = presetText;
}
I have paired the on blur action with a custom keystroke script that works to automatically add a hyphen after the 6th, 9th and 11th characters. I also have a limit of 16 characters set for the field.
// Get the current value of the field, removing any existing hyphens
var v = event.value.replace(/-/g, "");
// Check if the input has reached the 6th character
if (v.length > 6) {
// Add a hyphen after the 6th character
v = v.substring(0, 6) + "-" + v.substring(6, v.length);
}
// Update the field with the formatted value
event.value = v;
// Check if the input has reached the 9th character
if (v.length > 9) {
// Add a hyphen after the 9th character
v = v.substring(0, 9) + "-" + v.substring(9, v.length);
}
// Update the field with the formatted value
event.value = v;
// Check if the input has reached the 11th character
if (v.length > 11) {
// Add a hyphen after the 11th character
v = v.substring(0, 11) + "-" + v.substring(11, v.length);
}
// Update the field with the formatted value
event.value = v;
My problem is:
1) If I delete any of the characters of the preset text, it will reset the entire field to the preset text. It is not an issue if the preset text is the only thing in the field because if you delete anything, it will reset to the preset text. It becomes an issue when you have filled out the field with any number of other characters up to the 16 limit and you delete any character of the preset text because it will then reset the field to the preset text deleting all the other characters.
2) The character limit is 16 but when you are actively typing, it doesn't account for the three (3) hyphens until the end so the user is able to type in 19 characters actually.
My questions are:
1) If the user is filling out the field or has filled out the field and accidentally deletes any characters of the preset text, how can you just reset the preset text and preserve the other remaining characters and not reset the entire field to the preset text?
2) How can I prevent the user from exceeding the 16 character limit while typing?
