簡體   English   中英

我希望只有在驗證HTML5表單輸入后才能運行javascript函數

[英]I want to have a javascript function run only after HTML5 form input has been validated

我看到有人問過這個問題的變體,但是我看不到可以用來解決問題的任何答案。

我正在嘗試在提交並驗證HTML5表單后運行javascript函數。 我嘗試使用onSubmit。 在這種情況下,驗證會在輸入表單時進行,但是Submit不會執行任何操作,並且javascript函數永遠不會運行。 也就是說,我單擊了提交按鈕,我的輸入窗口消失了,但是我本應在提交時看到的消息沒有出現,並且從onSubmit調用的腳本沒有運行。 該代碼如下所示:

我嘗試使用onClick而不是onSubmit。 在這種情況下,如果我按下Enter鍵或在表單輸入中的任意位置單擊“提交”按鈕,則不會進行HTML5驗證,並且將提交表單。 除了使用onClick而不是onSubmit之外,其余代碼與上述代碼相同。

我嘗試在提交之后運行腳本是什么都沒關系。 使用onClick會導致腳本運行,但輸入未經驗證,在這種情況下,腳本將按預期運行。 這是我用作表單輸入的HTML:

<form id="myForm">
    <fieldset>
      <table>
        <tr>
          <td><label for="rfiTitle" style="font-weight: bold">RFI Title</label><label style="color:red; font:bold">**</label></td>
          <td><input type="text" maxlength = "200" name="rfiTitle" id="rfiTitle" form="myForm" size="40" placeholder="short summary, max length 200 characters" required></td>
        </tr>
        <tr>
          <td><label for="submitter" style="font-weight: bold">Submitter's Name</label><label style="color:red; font:bold">**</label></td>
          <td><input type="text" maxlength = "100" name="submitter" id="submitter" form="myForm" size="40" placeholder="full name, max length 100 characters" required></td>
        </tr>
        <tr>
          <td><label for="submitterEmail" style="font-weight: bold">Submitter's Email</label><label style="color:red; font:bold">**</label></td>
          <td><input type="email" name="submitterEmail" id="submitterEmail" form="myForm" size="40" placeholder="full email" required></td>
        </tr>
      </table>
     </fieldset>
<input type="submit" value="Submit" onsubmit="this.value='The form is uploading..';
         google.script.run.withSuccessHandler(fileUploaded).formHandler(this.parentNode); return false;">
</form>

我希望僅在成功提交后才運行該函數,並在其中填寫必填字段。根據我對stackoverflow的了解,聽起來我需要使用以下內容:

document.getElementById('myform').onsubmit = function(e) {
   Logger.log("into onsubmit fct:"+e);
    generateGUTS();
    e.preventDefault();
}
function generateGUTS(){
    google.script.run.withSuccessHandler(fileUploaded).formHandler(this.parentNode);
                    return false;
    alert('Generating GUTS ticket');
}

但是,我不知道如何在HTML輸入中使用它。 任何幫助將不勝感激。 謝謝。

只需添加腳本標簽,然后添加您的功能

<script type="text/javascript">

 document.getElementById('myform').onsubmit = function(e) {
   Logger.log("into onsubmit fct:"+e);
    generateGUTS();
    e.preventDefault();
}
function generateGUTS(){
    google.script.run.withSuccessHandler(fileUploaded).formHandler(this.parentNode);
                    return false;
    alert('Generating GUTS ticket');
}

</script>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM