簡體   English   中英

Wy 是我的表單提交事件偵聽器不起作用

[英]Wy is my form submit event listener is not working

我有一個表單,我試圖在用戶提交表單時監聽事件。 這是我的代碼:

html:

 const form = document.forms['testRegForm'] form.addEventListener('submit', e => { e.preventDefault() alert("Test"); var x = document.forms["required"]["mobile"].value; if (x == "") { alert("Mobile Number is required"); return false; }else { alert(x) fetch(scriptURL, { method: 'POST', body: new FormData(form)}) .then(response => alert('Your request is submitted. We will get in touch with you soon') ) .catch(error => alert(error.message)) } })
 <form name="testRegForm" style="font-family: Aladin;" > <p>Register using mobile Number: </p> <input type="number" placeholder="Number" pattern="\\d{3}[\\-]\\d{3}[\\-]\\d{4}" name="mobile" maxlength="10" required><br><br> <button type="submit">Submit</button> <p></p> </form>

但是單擊提交按鈕時事件偵聽器不起作用。 未顯示警報 - “測試”這一事實證實了這一點。 我哪里錯了?

您的事件確實在觸發,只是由於引用input的錯誤而沒有完成。 此外,請確保script位於結束body標記之前,以便在遇到script時完全解析 HTML。

const form = document.forms['testRegForm']替換為const form = document.querySelector("form")並使用有效選擇器修改對input的引用,如下所示。

 <!doctype html> <html> <head> <title>test</title> </head> <body> <form name="testRegForm" style="font-family: Aladin;" > <p>Register using mobile Number: </p> <input type="number" placeholder="Number" pattern="\\d{3}[\\-]\\d{3}[\\-]\\d{4}" name="mobile" maxlength="10" required><br><br> <button type="submit">Submit</button> <p></p> </form> <script> // A standard API for locating a DOM element is .querySelector() // which takes any valid CSS selector: const form = document.querySelector("form"); // Get your DOM references that you'll work with more than once // only once, so this has been moved outside of the event callback. // Also, "mobile" isn't an attribute, so your selector wasn't working // for it. And, it's best to get references to DOM elements, rather // than a particular property of an element so that if you decide you // want a difference property value, you've already got the element // reference and won't need to scan for it again. var x = document.querySelector("[required][name='mobile']"); form.addEventListener('submit', e => { e.preventDefault(); alert("Test"); if (x.value == "") { alert("Mobile Number is required"); return false; }else { alert(x.value); fetch(scriptURL, { method: 'POST', body: new FormData(form)}) .then(response => alert('Your request is submitted. We will get in touch with you soon') ).catch(error => alert(error.message)) } }); </script> <body> </html>

暫無
暫無

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

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