jQuery去除数字空格及获取输入值去空格后长度问题排查
Fix for Calculating Trimmed Input Value Length
Let's sort out this issue—your current code is accidentally calculating the length before removing spaces, which is why it's giving you the wrong count. You're trying to strip spaces from the length number (like turning "10" into "10", which does nothing) instead of the actual input text.
Here's the corrected code, with extra improvements to handle clearing the error message when the user focuses back on the input:
$('.phoneNumber1').on('blur', function(){ // Get the input value, remove ALL spaces first const rawValue = $(".phoneNumber1").val(); const trimmedValue = rawValue.replace(/ /g, ''); // Calculate length of the trimmed value const finalCount = trimmedValue.length; if(finalCount > 9) { // Only add the error if it doesn't already exist to avoid duplicates if(!$(".number-denied").length) { $(".phoneNumber1").after("<div class='number-denied'> Zadávejte bez předvolby</div>"); } } }).on('focus', function(){ // Remove the error message when user focuses back on the input $(".number-denied").remove(); });
Key Changes Explained:
- Trim first, then count: We now take the input's raw value, remove all spaces with
replace(/ /g, ''), then get the length of that trimmed string. This gives you the correct character count without spaces. - Prevent duplicate error messages: Added a check to make sure we only add the error div if it doesn't already exist—no more multiple error boxes popping up on repeated blurs.
- Clean up on focus: Added a
focushandler to remove the error message when the user starts editing again, which makes the UX smoother.
If you only want to remove leading/trailing spaces (not all spaces in the middle), you could replace replace(/ /g, '') with trim() instead—just adjust based on your exact needs!
内容的提问来源于stack exchange,提问作者Lion Dirty
相关产品推荐
相关产品推荐

