HTML输入框自动为每10位手机号添加分隔符的代码优化需求
Solution for Automatic Semicolon Separation for Multiple 10-Digit Phone Numbers
Got it, let's fix this issue! The original code only works for the first 10 digits because it relies on a fixed num variable that doesn't account for the semicolons added later, and it doesn't handle edits or deletions well. Here's a robust solution that supports multiple 10-digit phone numbers with automatic semicolon separation:
$(document).ready(function () { $("#editMobile").on('keyup', function (e) { // Ignore control keys (backspace, delete, arrow keys) to avoid unnecessary formatting const controlKeyCodes = [8, 46, 37, 38, 39, 40]; if (controlKeyCodes.includes(e.keyCode)) return; // Step 1: Clean input to keep only digits (remove existing semicolons or non-numeric chars) const rawDigits = $(this).val().replace(/[^\d]/g, ''); // Step 2: Split digits into chunks of 10 const mobileChunks = []; for (let i = 0; i < rawDigits.length; i += 10) { mobileChunks.push(rawDigits.slice(i, i + 10)); } // Step 3: Join chunks with semicolons for formatted output const formattedValue = mobileChunks.join(';'); // Step 4: Preserve cursor position (critical for good user experience) const originalCursorPos = this.selectionStart; const originalInputLength = $(this).val().length; $(this).val(formattedValue); // Adjust cursor position to match user's input flow const newInputLength = formattedValue.length; let adjustedCursorPos = originalCursorPos + (newInputLength - originalInputLength); this.setSelectionRange(adjustedCursorPos, adjustedCursorPos); }); });
Key Improvements Over the Original Code:
- Handles Edits & Deletions: The code cleans and re-formats the input every time, so if the user deletes a semicolon or a digit, it automatically re-adjusts the formatting.
- Ignores Control Keys: We skip formatting when the user presses backspace, arrow keys, etc., to avoid disrupting their input flow.
- Cursor Position Preservation: This is a big one—users hate when the cursor jumps to the end of the input box while typing. This code keeps the cursor where they expect it.
- Robust Input Cleaning: Removes any non-numeric characters, so accidental spaces or other symbols don't break the formatting.
Extra Optimizations:
- Limit Maximum Input: If you want to restrict to 5 phone numbers, add a
maxlengthattribute to your input (5*10 digits + 4 semicolons = 54 characters):<input id="editMobile" type="text" maxlength="54"> - Final Validation (Optional): Add a blur event to validate that all completed phone numbers are exactly 10 digits (except the last one if it's still being typed):
$("#editMobile").on('blur', function () { const segments = $(this).val().split(';'); const invalidSegments = segments.filter(seg => seg.length > 0 && seg.length !== 10); if (invalidSegments.length > 0) { alert("Please ensure all completed phone numbers are 10 digits long!"); } });
内容的提问来源于stack exchange,提问作者Sunil Sharma
相关产品推荐
相关产品推荐

