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

HTML表单必填字段校验异常:hover有提示但提交不触发错误提示

问题成因

  • 核心问题1:所有带required属性的输入控件没有被包裹在<form>标签中。HTML原生表单校验规则仅在<form>标签的提交动作触发时才会执行,你当前的代码没有表单容器,自然不会触发校验逻辑。
  • 核心问题2:你的按钮均为普通点击触发自定义函数的按钮,没有触发表单提交行为。即使有<form>容器,直接执行自定义JS函数的逻辑也会绕过原生表单校验流程。
  • 附加问题:<textarea>标签内部已经写入了默认文本Enter the paragraph here...,required会判定该字段已有内容,就算触发校验也不会对该字段弹出提示。另外<textarea>本身不存在value属性,你写的value=""属于无效属性。

修复方案

  1. 把所有输入控件、按钮都包裹在<form>标签内
  2. 将需要触发校验的按钮类型改为type="submit",同时监听表单的submit事件来执行你的计数逻辑,要阻止默认提交跳转行为的话在JS函数里加e.preventDefault()即可
  3. 删掉<textarea>内部的默认文本,仅保留placeholder属性做提示
  4. 移除<textarea>上无效的value属性

修复后代码示例

<!-- 新增form标签包裹所有控件 -->
<form id="wordCountForm">
    <div>Web Word Count App</div>
    <div>
        <textarea id="paragraph" rows="5" cols="35" placeholder="Enter the paragraph here..." required></textarea>
    </div>
    <div>
        <input type="text" id="word" placeholder="Enter the keyword here..." required>
    </div>
    <div>
        <input type="text" class="display" id="display-1" readonly placeholder="Total word count = 0 "><br>
        <input type="text" class="display" id="display-2" readonly placeholder="Keyword does not exist!"><br>
        <input type="text" class="display" id="display-3" readonly placeholder="Total keyword appearances = 0">
    </div>
    <div>
        <button type="submit" class="wwcbutton" data-action="wordCount">Total words?</button>
    </div>
    <div>
        <button type="submit" class="wwcbutton" data-action="checkKeyword">Check keyword appearance</button>
    </div>
    <div>
        <button type="submit" class="wwcbutton" data-action="keywordCount">Total keyword appearances?</button>
    </div>
    <div>
        <button type="button" class="wwcbutton-clear" onclick="Clear();">Clear</button>
    </div>
</form>

<script>
// 监听表单提交事件触发校验和对应逻辑
document.querySelector('#wordCountForm').addEventListener('submit', function(e) {
    e.preventDefault()
    const action = e.submitter.dataset.action
    switch(action) {
        case 'wordCount':
            Word_count()
            break
        case 'checkKeyword':
            Check()
            break
        case 'keywordCount':
            keyword_count()
            break
    }
})
</script>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 07:57:01