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

表单提交后如何让未填写的文本输入框红色边框持续显示?

问题原因

你点击提交按钮后表单触发了默认提交行为,页面会刷新重置,所以你手动设置的红色边框和用户已输入的内容都会被清空,才会出现仅显示一秒的情况。

解决方法

核心是校验不通过时阻止表单的默认提交行为,修改代码如下:

1. 修改HTML提交按钮代码

给onclick事件加上return,接收函数返回的布尔值来控制是否提交:

<form id="contactInfo" name="contactInfo">
  <label>Name: </label>
  <input type="text" name="name"><br/><br/>
  <label>E-mail: </label>
  <input type="text" name="email"><br/><br/>
  <label>Message:</label><br/>
  <textarea rows="10" cols="80" name="message"></textarea><br/><br/>
  <!-- 此处新增return,接收校验函数的返回值 -->
  <input type="submit" name="sendMessage" onclick="return messageChecker()">
</form>

注:input是单标签,不需要写</input>闭合,上述代码已同步修正冗余写法

2. 修改JavaScript校验函数

校验不通过时返回false,阻止表单提交:

function messageChecker(){
  // 新增trim()清理前后空格,避免用户只输入空格的无效提交
  let x = document.forms["contactInfo"]["name"].value.trim();
  let y = document.forms["contactInfo"]["email"].value.trim();
  let z = document.forms["contactInfo"]["message"].value.trim();
  if (x=="" || y=="" || z==""){
    alert("Please fill out the indicated field(s).");
    if (x==""){
      document.forms["contactInfo"]["name"].style.border = "1px solid red";
    } else {
      // 字段已填写则清除之前的红色边框
      document.forms["contactInfo"]["name"].style.border = "";
    }
    if (y==""){
      document.forms["contactInfo"]["email"].style.border = "1px solid red";
    } else {
      document.forms["contactInfo"]["email"].style.border = "";
    }
    if (z==""){
      document.forms["contactInfo"]["message"].style.border = "1px solid red";
    } else {
      document.forms["contactInfo"]["message"].style.border = "";
    }
    // 校验不通过,返回false阻止表单提交
    return false;
  }
  // 全部校验通过,返回true允许正常提交
  return true;
}

可选体验优化

如果需要用户输入内容时自动清除红色边框,可以给每个输入框加oninput事件:

<input type="text" name="name" oninput="this.style.border=''">

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 21:45:03