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

输入框输入内容时显示表单,清空内容时如何隐藏该表单?

解决输入框清空时隐藏表单的问题

先给你指出代码里的几个问题,再给你完整的解决方案:

  1. 输入框的type写错了,应该是text而不是text6,这个先修正,避免浏览器识别异常。
  2. 你用onClick触发表单显示,会导致用户点击输入框哪怕没输入内容也显示表单,不符合「输入内容时显示」的逻辑。
  3. 输入框没有onsubmit事件,这个事件是给表单元素用的,所以你那段隐藏表单的代码根本不会触发。

下面是修正后的完整代码,实现「输入内容显示表单,清空内容隐藏表单」的需求:

<input style="margin-right: 5px;" type="text" name="outstanding1" id="outstanding" />

<form id="form2" style="display: none;">
  <!-- 这里放入你的第二个表单内容 -->
</form>

<script>
  const outstandingInput = document.getElementById('outstanding');
  const form2 = document.getElementById('form2');

  // 监听输入框内容变化,实时判断显示/隐藏
  outstandingInput.addEventListener('input', function() {
    // 去掉首尾空格,避免输入空格误触发显示
    if (this.value.trim() !== '') {
      form2.style.display = 'block';
    } else {
      form2.style.display = 'none';
    }
  });
</script>

如果想保留「点击输入框就显示表单」的逻辑,同时清空内容时隐藏,可以用这个版本:

<input style="margin-right: 5px;" type="text" name="outstanding1" id="outstanding" />

<form id="form2" style="display: none;">
  <!-- 表单内容 -->
</form>

<script>
  const outstandingInput = document.getElementById('outstanding');
  const form2 = document.getElementById('form2');

  // 点击输入框直接显示表单
  outstandingInput.addEventListener('click', function() {
    form2.style.display = 'block';
  });

  // 内容清空时自动隐藏
  outstandingInput.addEventListener('input', function() {
    if (this.value.trim() === '') {
      form2.style.display = 'none';
    }
  });
</script>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 18:50:07