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

表单需点击两次提交按钮才显示成功/错误消息求助

联系表单提交需点击两次按钮才显示成功消息问题

我使用HTML、CSS、JavaScript结合PHPMailer后端搭建了一个联系表单,可将表单信息发送至我的邮箱和Google表格。表单每次提交都能成功,但需要点击两次提交按钮才会显示成功消息。

提交函数

function submitForm() {
  if (nameInputValidation && emailInputValidation && numberOfPeopleValidation && phoneInputValidation && isChecked && foundAboutUsValidation) {
    submissionAlert.classList.add("show");
    successMessage.classList.add("show");
    const scriptURL = "[GOOGLE-SCRIPT]";
    fetch(scriptURL, { method: "POST", body: new FormData(form) })
      .then(successMessage.classList.add("show"))
      .catch(errorMessage.classList.add("show"));

// Send data to PHP script with AJAX request
var xhr = new XMLHttpRequest();
xhr.open("POST", "./phpmailer/index.php", true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.onreadystatechange = function () {
  if (xhr.readyState == 4 && xhr.status == 200) {
    successMessage.classList.add(".show");
  } else {
    errorMessage.classList.add(".show");
  }
};

// Get form data
var name = document.getElementById("name").value;
var email = document.getElementById("email").value;
var message = document.getElementById("message").value;
var dateFor = document.getElementById("date-for").value;
var phoneNumber = document.getElementById("phoneNumber").value;
var numberOfPeople = document.getElementById("numberOfPeople").value;
var foundAboutUs = document.getElementById("foundAboutUs").value;

xhr.send(
  "name=" +
    name +
    "&email=" +
    email +
    "&message=" +
    message +
    "&phoneNumber=" +
    phoneNumber +
    "&date-for=" +
    dateFor +
    "&numberOfPeople=" +
    numberOfPeople +
    "&foundAboutUs=" +
    foundAboutUs
);
phoneInput.parentElement.style.display = "none";
  } else {
    checkInputs();
  }
}

精简后的HTML表单

<form name="contact-form" class="contact" id="contact-form" onsubmit="event.preventDefault(); submitForm();">
  <div class="form-group">
    <button type="submit" name="submit" value="Send Message" class="btn btn-primary" id="submit-btn">Submit</button>
  </div>
</form> 

我尝试过多种解决方案:

  • 在form标签上添加onSubmit="event.preventDefault(); submitForm();"
  • 在button元素上添加onClick="onSubmit('event)",并在函数中阻止默认事件
  • 使用事件监听器,通过匿名函数处理提交逻辑
  • 为button添加Click事件监听器,或为Form添加onSubmit事件监听器

当设置为点击一次即可提交时,错误和成功消息无法显示,推测是preventDefault未生效;若页面不刷新,则必须点击两次按钮才能显示消息。尝试过相关方案,但均未解决问题,目前要么需点击两次按钮,要么preventDefault失效导致页面刷新,无法正常显示消息。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 12:05:39