繁体   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