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

如何实现formsubmit.co表单无跳转提交并禁用按钮60秒

问题分析与修复方案

原代码核心问题

  • 提前返回阻断后续逻辑:return false;写在fetch请求之后,函数执行到此处直接终止,修改按钮状态、定义倒计时的代码完全不会运行。
  • 异步请求未等待完成:fetch是异步操作,原代码未等待表单提交请求结束就尝试修改按钮状态(即使代码能执行到这一步),逻辑顺序错误。
  • 函数定义后未调用:hideFreeEntryButton仅在判断里定义,但从未触发调用,倒计时逻辑不会生效。
  • 冗余点击事件:按钮的onclick="hideFreeEntryButton"无效,且和表单提交逻辑冲突,无需保留。

修复后的完整代码

<div style="background-color: #0e1b4d; padding-left: 10%; padding-right: 10%;">
<form method="POST" class="my-form" onsubmit="return submitForm()">
     <label>Full Name <sup style="color: red; font-size: 13px;">*</sup></label><br>
     <input class="freeEntryInput" type="text" name="name" placeholder="Full Name" required><br>
     <label>Email Address <sup style="color: red; font-size: 13px">*</sup></label><br>
     <input class="freeEntryInput" type="email" name="email" placeholder="Email Address" required><br>
     <label style="font-weight: normal; font-size: 12px;"><input type="checkbox" name="contest rules" required>  I have read and agree to the <span class="contestRulesLink">Contest Rules</span></label>
     <input type="hidden" name="_captcha" value="false">
     <input type="text" name="_honey" style="display:none">
     <button id="freeEntryButton" type="submit">Submit Form</button>
</form>
</div>
<script> 
async function submitForm() {
    const form = document.querySelector('.my-form');
    const formData = new FormData(form);
    const url = 'https://formsubmit.co/<email>';
    const button = document.getElementById('freeEntryButton');

    // 提前禁用按钮,防止重复提交
    button.disabled = true;
    button.innerHTML = "Submitting...";

    try {
        // 等待表单提交请求完成
        await fetch(url, {
            method: 'POST',
            body: formData
        });
        
        // 请求成功后启动倒计时
        startCountdown(button);
    } catch (error) {
        // 请求失败时恢复按钮状态
        button.disabled = false;
        button.innerHTML = "Submit Form";
        console.error('表单提交失败:', error);
    }

    // 阻止表单默认跳转
    return false;
}

function startCountdown(button) {
    let secs = 10; // 测试用10秒,后续可改为60秒
    button.innerHTML = `${secs}s remains`;
    
    const countdown = setInterval(() => {
        secs--;
        button.innerHTML = `${secs}s remains`;
        
        if (secs < 0) {
            clearInterval(countdown);
            button.disabled = false;   
            button.innerHTML = "Submit Form"; 
        }
    }, 1000);
}
</script>

关键修改说明

  1. 用async/await处理异步请求:确保表单提交完成后再执行按钮状态修改,逻辑顺序更合理。
  2. 调整return false位置:移到函数末尾,保证所有逻辑执行完毕后再阻止表单跳转。
  3. 提前禁用按钮:发起请求前就禁用按钮,避免用户重复提交,同时给出“Submitting...”的状态提示。
  4. 拆分倒计时函数:将倒计时逻辑单独封装,代码更清晰,且在请求成功后直接调用。
  5. 添加错误处理:提交失败时恢复按钮状态,避免用户无法再次提交。
  6. 移除无效点击事件:按钮状态逻辑统一由submitForm函数处理,消除冲突。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 22:10:24