javascript - Wy 是我的表单提交事件监听器不工作
问题描述
我有一个表单,我正在尝试在用户提交表单时收听事件。这是我的代码:
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 时完全解析 HTML。
const form = document.forms['testRegForm']
用一个有效的选择器替换const form = document.querySelector("form")
并修改您对input
as 的引用,如下所示。
<!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>
推荐阅读
- hybris - 如何知道 Hybris 中现有扩展的模板名称
- angular - NativeScript Google Maps SDK - 标记随机跳跃 W/多个 MapViews
- java - RCP 应用程序中的通知小部件
- javascript - For循环 - 如何引用状态中的对象?
- javascript - 用于装箱算法的画布到 SVG 的实现
- r - 在 r 中重命名 ts 对象的月份
- windows - 在 Winapi 中创建 24 位 BITMAP
- infopath - 如何确保自动填充的用户名不会被 InfoPath 中的另一个用户名替换
- c# - 动画过渡统一
- angular - Angular 8 更新后未构建 Angular MomentDateTimeAdapter