我有一个表单,当用户提交表单时,我正在尝试听事件。这是我的代码:
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>
但是,当单击“提交”按钮时,事件侦听器不起作用。通过未显示警报“测试”这一事实来验证这一点。我在哪里错了?
答案 0 :(得分:0)
您的事件确实在触发,只是由于引用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>