JavaScript:提交后在表单下显示元素

时间:2019-05-06 21:03:55

标签: javascript html forms

我有一个表单,我想在有人输入电子邮件并提交表单后显示一些内容。表单应隐藏,内容应可见。

我已经写了一些JavaScript,但是当我们键入电子邮件并提交表单时,页面会刷新,并且表单又回到了内容上。

我为onClick事件提供了部分JavaScript,但是它仍然不完整:

function myFunction() {
var x = document.getElementById("formhide");
if (x.style.display === "none") {
  x.style.display = "block";
} else {
  x.style.display = "none";
}
}
div {
  width: 200px;
  background: red;
  padding: 30px;
  height: 300px;
}

form {
  margin: 15px;
  position: absolute;
  width: 200px;
  padding: 15px;
  height: 300px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: rgba(255, 255, 255, 0.5);
}
    
<form id="formhide" method="post">
  <input type="email" name="email-address" required>
  <button onclick="myFunction()">Click Me</button>
</form>

<div>
  <h2>ESKETIT</h2>
  <p>Lorem ipsum dolor sit, amet consectetur adipisicing elit. Mollitia voluptatibus excepturi voluptates ratione aut placeat in maxime obcaecati reprehenderit! Modi provident nulla nostrum obcaecati esse, tempore commodi excepturi quae culpa.</p>
</div>

有人向表单提交电子邮件,表单将长时间隐藏和显示内容。

1 个答案:

答案 0 :(得分:2)

有几种方法可以实现您想要的。通常,类似AJAX的请求通过JavaScript将表单数据发布到服务器,这意味着一旦AJAX请求完成,您就可以更新文档的HTML。

使用您的代码实现此目标的一种方法是通过fetch()方法和FormData对象,如下所示:

function myFunction(event) {

  /* Prevent button causing default browser submit */
  event.preventDefault();

  /* Get form element */
  const form = document.getElementById('formhide');

  /* Create form data object from form element which contains post data */
  let formData = new FormData(form);

  /* Issue "ajax request" to server. Change /post-to-url to the appropriate 
  url on your server */
  fetch('/post-to-url', {
      body: formData,
      method: "post"
    })
    .then(function() {
      /* When submit successfully completed, hide form */
      form.style.display = "none";

      /* Show success message */
      const successMessage = document.getElementById('success-message');
      successMessage.style.display = 'block';

    })
    .catch(function(error) {
      console.log('Error', error);
    });


}
#success-message {
  display: none;
}
<form id="formhide" method="post">
  <input type="email" name="email-address" required>
  <button onclick="myFunction(event)">Click Me</button>
</form>

<p id="success-message"> Form sent - this is the message that displays after submit </p>

<div>
  <h2>ESKETIT</h2>
  <p>Lorem ipsum dolor sit, amet consectetur adipisicing elit. Mollitia voluptatibus excepturi voluptates ratione aut placeat in maxime obcaecati reprehenderit! Modi provident nulla nostrum obcaecati esse, tempore commodi excepturi quae culpa.</p>
</div>