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

如何实现输入框错误消息的onblur显示与onfocus隐藏

解决输入框焦点切换时错误消息的显示问题

这问题很常见,咱们只需要给输入框加上onfocus事件处理,同时优化一下check函数的逻辑就能完美解决。

修改要点:

  • 给输入框添加onfocus事件,绑定一个清除错误提示的函数
  • 优化check函数:输入为空时显示错误,输入有内容时隐藏错误(避免用户输入后错误提示还残留)

修改后的完整代码:

<form action="sign_in.php" method="post" id="sign_in_form">
  <div class="form-group">
    <label for="email" style="font-weight: bold; cursor: text;"><span style="color:red;">* </span>Email Address</label>
    <input type="text" name="email_3" id="email_3" class="form-control form-control-lg" onblur="check();" onfocus="clearError();" value="" style="width:455px; background-color:#EEEEEE;">
  </div>
  <div id="errorname"></div>
  <script>
    function check(){
      const input = document.getElementById('email_3');
      const errorElement = document.getElementById('errorname');
      if(input.value.trim() === ''){ // 用trim()处理纯空格的情况,判断更严谨
        errorElement.innerHTML = "This is an invalid email address";
      } else {
        // 输入不为空时清空错误提示
        errorElement.innerHTML = '';
      }
    }

    function clearError(){
      document.getElementById('errorname').innerHTML = '';
    }
  </script>
</form>

逻辑说明:

  1. 当用户点击输入框(触发onfocus),clearError()会立刻清空错误提示,让输入体验更友好
  2. 当用户点击外部离开输入框(触发onblur),check()会检查输入内容:
    • 如果输入为空(包括全空格的情况),显示错误消息
    • 如果输入有内容,清空错误消息,避免残留

内容的提问来源于stack exchange,提问作者Black P

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.12 03:47:34