You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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 focus handler 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 09:45:46