Im working on a school project, creating a “webshop” (its just for practice – not real).
Im trying to format the input for the users card number so that it looks like:
1234 5678 9101 1112.
when typing the cardnumber formatting works, but when the user starts backspacing, problems arise.
All is fine when backspacing through the string – i’ve created a function that skips the spaces, and made sure that the user cannot interact with them, but when we reach the first 4 digits (1234) backspace deletes two characters at a time instead of one, and i cannot figure out why.
heres my code for handling backspace and formatting in the cardNumber input field:
//handle formatting for the cardnumber
formatCardNumber(value) {
let formattedValue = value.replace(/D/g, ''); // Remove all non-digit characters
// Insert a space after every 4 digits
if (formattedValue.length <= 16) {
formattedValue = formattedValue.replace(/(d{4})(?=d)/g, '$1 ');
} else {
formattedValue = formattedValue.substring(0, 16); // Limit to 16 digits
formattedValue = formattedValue.replace(/(d{4})(?=d)/g, '$1 '); // Add spaces
}
return formattedValue; // Return the formatted value
},
// Handle backspace behavior specifically for card number inputs
handleCardNumberBackspace(cardNumberInput, e) {
if (e.key === 'Backspace') { // Check if the Backspace key is pressed
let value = cardNumberInput.value.replace(/D/g, ''); // Remove spaces and non-digits
let cursorPos = cardNumberInput.selectionStart; // Get the current cursor position
if (cursorPos > 0 && cardNumberInput.value[cursorPos - 1] === ' ') {
// If the cursor is before a space, remove the preceding digit and the space
cardNumberInput.value = value.substring(0, cursorPos - 1) + value.substring(cursorPos);
cardNumberInput.setSelectionRange(cursorPos - 1, cursorPos - 1); // Update cursor position
} else {
// Remove the digit at the cursor position
cardNumberInput.value = value.substring(0, cursorPos - 1) + value.substring(cursorPos);
cardNumberInput.setSelectionRange(cursorPos - 1, cursorPos - 1); // Update cursor position
}
cardNumberInput.value = this.formatCardNumber(cardNumberInput.value); // Reapply formatting
}
},
Albertpinn is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
1
Try this code. May solve your problem.
function formatInput(el){
let cardEntered=el.value.replaceAll(" ","");
let outTXT="";
for(let a=0;a<cardEntered.length;a+=4){
outTXT+=cardEntered.substr(a, 4)+" ";
}
el.value=outTXT.trim();
}
function getText(formatedTXT){
return formatedTXT.replaceAll(" ","");
}
<input type="text" onclick="alert(getText(this.value));" oninput="formatInput(this);" value="1234 5678 abcd"/>
AmirABD is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.