首页 > 解决方案 > 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>

但是单击提交按钮时事件侦听器不起作用。这通过未显示警报“测试”这一事实得到验证。我哪里错了?

标签: javascriptforms

解决方案


您的事件确实正在触发,只是由于引用input. 此外,请确保script位于结束body标记之前,以便在script遇到 HTML 时完全解析 HTML。

const form = document.forms['testRegForm']用一个有效的选择器替换const form = document.querySelector("form")并修改您对inputas 的引用,如下所示。

<!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>


推荐阅读