简体   繁体   中英

Jquery not functioning properly in Google Apps Script

I have this code:

index.html

<!DOCTYPE html>
<html>
    <div>
      <form id="email_subscribe">
        <input type="email" name="email" id="email" placeholder="Enter your email">
        <input type="submit" value="Subscribe">
      </form>
      <span id="thank_you" hidden="true">Thank you!</span>
    </div>

    <?!= HtmlService.createHtmlOutputFromFile('CSS').getContent(); ?>

    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
    <script>
      $( document ).ready(function() {
        $( "#email_subscribe" ).submit(function() {
          google.script.run.withSuccessHandler(function(ret){
            $("#email_subscribe").slideUp();
            $( "#thank_you" ).show("slow");
            console.log(ret);
          }).addEmail(this); //"this" is the form element
         }); 
       });
    </script>
</html>

and this one:

Code.gs

function doGet() {


var html = HtmlService.createTemplateFromFile('index').evaluate()
            .setTitle("Web App 2").setSandboxMode(HtmlService.SandboxMode.NATIVE);
  return html;
}

function addEmail(form){
      Logger.log(form.email);
      return 200;
}

The "Thank you message" is not showing up upon submitting the form. Can you please tell me what am I doing wrong. Thank you.

With IFRAME mode however HTML forms are allowed to submit, and if a form element has no action attribute specified it will submit to a blank page. Offical Documentation

The solution is to add a return false; or event.preventDefault() at the end of your submit function to tell the browser to cancel the event, your code should look like this:

$( "#email_subscribe" ).submit(function() {
  google.script.run.withSuccessHandler(function(ret){
    $("#email_subscribe").slideUp();
    $( "#thank_you" ).show("slow");
    console.log(ret);
  }).addEmail(this); //"this" is the form element
 return false;
 }); 

You can also implement the solution suggested in the docs, create an EventListener to prevent all form submitions on load with this code:

<script>
  // Prevent forms from submitting.
  function preventFormSubmit() {
    var forms = document.querySelectorAll('form');
    for (var i = 0; i < forms.length; i++) {
      forms[i].addEventListener('submit', function(event) {
        event.preventDefault();
      });
    }
  }
  window.addEventListener('load', preventFormSubmit);
</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM