提交后显示 toast 和清除表单

Posted

技术标签:

【中文标题】提交后显示 toast 和清除表单【英文标题】:Display toast and clear form after submit 【发布时间】:2021-04-07 05:05:26 【问题描述】:

这是一个使用html CSSjavascript 的简单联系表格。输入表单提交按钮后,我无法收到消息。它会将我重定向到显示提交详细信息的页面,我不希望这种情况明显发生。我希望在单击提交按钮后收到一条 toast 消息,并重置表单。我添加了一个额外的按钮来检查 toast 的功能。我真的被困在这上面了!!

请帮忙!

form demo

(function() 
  // get all data in form and return object
  function getFormData(form) 
    var elements = form.elements;
    var honeypot;

    var fields = Object.keys(elements).filter(function(k) 
      if (elements[k].name === "honeypot") 
        honeypot = elements[k].value;
        return false;
      
      return true;
    ).map(function(k) 
      if (elements[k].name !== undefined) 
        return elements[k].name;
        // special case for Edge's html collection
       else if (elements[k].length > 0) 
        return elements[k].item(0).name;
      
    ).filter(function(item, pos, self) 
      return self.indexOf(item) == pos && item;
    );

    var formData = ;
    fields.forEach(function(name) 
      var element = elements[name];

      // singular form elements just have one value
      formData[name] = element.value;

      // when our element has multiple items, get their values
      if (element.length) 
        var data = [];
        for (var i = 0; i < element.length; i++) 
          var item = element.item(i);
          if (item.checked || item.selected) 
            data.push(item.value);
          
        
        formData[name] = data.join(', ');
      
    );

    // add form-specific values into the data
    formData.formDataNameOrder = JSON.stringify(fields);
    formData.formGoogleSheetName = form.dataset.sheet || "responses"; // default sheet name
    formData.formGoogleSendEmail = form.dataset.email || ""; // no email by default

    return 
      data: formData,
      honeypot: honeypot
    ;
  

  function handleFormSubmit(event)  // handles form submit without any jquery
    event.preventDefault(); // we are submitting via xhr below
    var form = event.target;
    var formData = getFormData(form);
    var data = formData.data;

    // If a honeypot field is filled, assume it was done so by a spam bot.
    if (formData.honeypot) 
      return false;
    

    disableAllButtons(form);
    var url = form.action;
    var xhr = new XMLHttpRequest();
    xhr.open('POST', url);
    // xhr.withCredentials = true;
    xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    xhr.onreadystatechange = function() 
      if (xhr.readyState === 4 && xhr.status === 200) 
        form.reset();
        var formElements = form.querySelector(".form-elements")
        if (formElements) 
          formElements.style.display = "none"; // hide form
        
        var thankYouMessage = form.querySelector(".thankyou_message");
        if (thankYouMessage) 
          thankYouMessage.style.display = "block";
        
      
    ;
    // url encode form data for sending as post data
    var encoded = Object.keys(data).map(function(k) 
      return encodeURIComponent(k) + "=" + encodeURIComponent(data[k]);
    ).join('&');
    xhr.send(encoded);
  

  function loaded() 
    // bind to the submit event of our form
    var forms = document.querySelectorAll("form.gform");
    for (var i = 0; i < forms.length; i++) 
      forms[i].addEventListener("submit", handleFormSubmit, false);
    
  ;
  document.addEventListener("DOMContentLoaded", loaded, false);

  function disableAllButtons(form) 
    var buttons = form.querySelectorAll("button");
    for (var i = 0; i < buttons.length; i++) 
      buttons[i].disabled = true;
    
  
)();
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>

<h2 class="content-head is-center">Contact Us!</h2>
<aside>
  <p>
    We would <em>love</em> to hear from you! </p>
  <p>Please use the <b><em>Contact Form</em></b> to send us a message.
  </p>
</aside>

<!-- START HERE -->
<link rel="stylesheet" href="https://unpkg.com/purecss@1.0.0/build/pure-min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css">
<!-- Style The Contact Form How Ever You Prefer -->
<link rel="stylesheet" href="style.css">

<form class="gform pure-form pure-form-stacked" method="POST" data-email="" action="https://script.google.com/macros/s/AKfycbxud2vvVuUj0YXOasdO50lQwPJc3FnoTZXdNtgRdaYnl70kKDlRO6nS/exec">
  <!-- change the form action to your script url -->

  <div class="form-elements">
    <fieldset class="pure-group">
      <label for="name">Name: </label>
      <input id="name" name="name" placeholder="What your Mom calls you" />
    </fieldset>

    <fieldset class="pure-group">
      <label for="message">Message: </label>
      <textarea id="message" name="message" rows="10" placeholder="Tell us what's on your mind..."></textarea>
    </fieldset>

    <fieldset class="pure-group">
      <label for="email"><em>Your</em> Email Address:</label>
      <input id="email" name="email" type="email" value="" required placeholder="your.name@email.com" />
    </fieldset>

    <fieldset class="pure-group">
      <label for="color">Favourite Color: </label>
      <input id="color" name="color" placeholder="green" />
    </fieldset>

    <fieldset class="pure-group honeypot-field">
      <label for="honeypot">To help avoid spam, utilize a Honeypot technique with a hidden text field; must be empty to submit the form! Otherwise, we assume the user is a spam bot.</label>
      <input id="honeypot" type="text" name="honeypot" value="" />
    </fieldset>

    <button class="button-success pure-button button-xlarge">
        <i class="fa fa-paper-plane"></i>&nbsp;Send</button>
  </div>

  <!-- Customise the Thankyou Message People See when they submit the form: -->
  <div class="thankyou_message" style="display:none;">
    <h2><em>Thanks</em> for contacting us! We will get back to you soon!</h2>
  </div>

</form>
<div class="toast" id="myToast" data-autohide="false">
  <div class="toast-header">
    <strong class="mr-auto text-primary">Toast Header</strong>
    <small class="text-muted">5 mins ago</small>
    <button type="button" class="ml-2 mb-1 close" data-dismiss="toast">&times;</button>
  </div>
  <div class="toast-body">
    Some text inside the toast body
  </div>
</div>
<button type="button" class="btn btn-primary show-toast">Show Toast</button>


<script>
  $(document).ready(function() 
    $(".show-toast").click(function() 
      $("#myToast").toast('show');
    );
  );
</script>

<!-- Submit the Form to Google Using "AJAX" -->
<script data-cfasync="false" src="form-submission-hanler.js"></script>
<!-- END -->

【问题讨论】:

也许我错过了它,但我看不到您在提交表单时分配要调用的 handleFormSubmit() 的位置。 好的,我会检查一下,你的意思是 onsubmit(); 【参考方案1】:

您可以在单击按钮时添加事件并使用 reset() 来重置表单值。在脚本部分添加以下代码:

$('.button-success').on('click', function(e)
        e.preventDefault()        //This stops page loading
        $("#myToast").toast('show'); //Show toast
        document.getElementsByName('data-form')[0].reset() //reset field values of the form
    )

将名称参数添加到您的表单标签以在此函数中访问它。 (例如:我已将名称添加为 'data-form')

【讨论】:

对不起,我应该在我的脚本中哪里添加它,你能指出吗? 在你的 将它添加到您的

以上是关于提交后显示 toast 和清除表单的主要内容,如果未能解决你的问题,请参考以下文章

Laravel 和 axios 提交后清除表单

使用jquery提交后清除表单[重复]

提交后清除有效表格

提交成功后如何清除表单?

在Angular 2中提交后如何清除表单?

使用ajax提交后如何清除ckeditor表单?