开发者问题收集

Javascript:如何使表单的“必填”部分正常工作?[关闭]

2022-06-24
86

我第一次尝试使用必需元素的注册页面。令人沮丧的是,这之前是可以工作的,但我想我做了一些改动,现在不行了,我搞不清楚我这里漏掉了什么。

我希望发生什么:当我点击提交按钮时,会发生以下两种情况之一。它会告诉我我尚未输入必需的值并且不会提交(如果我将值留空),或者它会提交(如果我输入了值)并将内容更改为“谢谢”并创建用户的对象,该对象将被添加到数组中。

目前发生的情况:我只能让其中一个或另一个工作,具体取决于我如何查询选择输入类型=提交按钮。如果我有 const submitButton = document.querySelector('button[type=submit]'); ,它确保我需要触发事件侦听器所需的值,但它实际上不会触发事件,我会在控制台中得到这个:

Uncaught TypeError: Cannot read properties of null (reading 'addEventListener')

如果我拿走按钮并有 const submitButton = document.querySelector('[type=submit]'); ,事件会按应有的方式触发(转到感谢消息,创建一个对象,添加到列表中),但如果必需的值为空,它不会阻止它提交。

我尝试了各种方法来重写它(包括'[type="submit"]'),但它不起作用,我想我在这里遗漏了一些简单的东西?任何帮助表示感谢。 CSS 完全可以工作,所以我会粘贴我的 html 和 js,以防有人需要它。

HTML:

<div class="rightside-content">

                    <div class="signup-title">
                        <h1>Sign up</h1>
                    </div>
                    <form class="join-form">

                        <ul>
                            <li><input type="text" name="username" class="username" placeholder="Username" required></li>

                            <li><input type="text" name="fullname" class="fullname" placeholder="Full Name" required></li>
                            
                            <li><input type="email" name="email" class="email" placeholder="Email Address" pattern=".+@gmail\.com" required></li>
                            
                            <li><input type="text" name="phone" class="phone" placeholder="Phone Number" required></li>

                            <li><input type="text" name="postcode" class="postcode" placeholder="Post Code" required></li>
                        
                            <li><input type="password" name="password" class="password" placeholder="Enter a password" required></li>
                        </ul>
                        <input type="submit">
                    </form>
                </div>

            </div>

        </div>

JS:

const submitButton = document.querySelector('[type="submit"]');
const registerForm = document.querySelector(".rightside-content");

const userName = document.querySelector(".username");
const fullName = document.querySelector(".fullname");
const emailAddress = document.querySelector(".email");
const contactNumber = document.querySelector(".phone");
const postCode = document.querySelector(".postcode");
const Password = document.querySelector(".password");

let users = [];
let user = {userName: userName.value, fullName: fullName.value, emailAddress: emailAddress.value, contactNumber: contactNumber.value, postCode: postCode.value, Password: Password.value};
let count = 0;

submitButton.addEventListener("click", (e) =>{
    e.preventDefault();

    user.userName = userName.value;
    user.fullName = fullName.value;
    user.emailAddress = emailAddress.value;
    user.contactNumber = Number(contactNumber.value);
    user.postCode = Number(postCode.value);
    user.Password = Password.value;

    users.push(user);
    console.log(users);
    console.log(users.length);

    registerForm.innerHTML = 'Thank you for joining!';
    registerForm.style.fontSize = '1.5rem';
    registerForm.style.fontFamily = 'Segoe UI, Tahoma, Geneva, Verdana, sans-serif';
    registerForm.style.textAlign = 'center';
    registerForm.style.marginTop = '50%'; 
    
    users[count] = user;
    count = count + 1;
})

为未来的人编辑:几个答案很有帮助,但如果您需要继续使用 [addEventListener] 元素,我发现将其作为 formname.addeventlistener("submit....) 也解决了我的问题(如 AchoVasilev 的评论所建议的)

3个回答

下面的代码可以以更少的代码编写和维护完成工作:

const users=[], msg=document.getElementById("msg");
document.querySelector("form").onsubmit=ev=>{let usr;
 users.push(usr=Object.fromEntries( [...ev.target.querySelectorAll("ul input")].map(e=>[e.name,e.value])));
 console.log(users);
 msg.textContent=`Thank you for joining, ${usr.fullname}!`
 return false;
}
form li {display:block}
<div class="rightside-content">
  <div class="signup-title">
    <h1>Sign up</h1>
  </div>
  <form class="join-form">
    <ul>
      <li><input type="text" name="username" class="username" placeholder="Username" required></li>
      <li><input type="text" name="fullname" class="fullname" placeholder="Full Name" required></li>
      <li><input type="email" name="email" class="email" placeholder="Email Address" pattern=".+@gmail\.com" required value="[email protected]"></li>
      <li><input type="text" name="phone" class="phone" placeholder="Phone Number" required></li>
      <li><input type="text" name="postcode" class="postcode" placeholder="Post Code" required></li>
      <li><input type="password" name="password" class="password" placeholder="Enter a password" required></li>
    </ul>
    <input type="submit">
  </form>
  <div id="msg"></div>
</div>
Carsten Massmann
2022-06-24

只需在表单上添加 onsubmit 事件,如下所示:

<form class="join-form" onsubmit="event.preventDefault(); return fn(this)">

并用以下函数替换 submitButton.addEventListener("click", (e) =>{.... } 。

function fn(e) {
            user.userName = userName.value;
            user.fullName = fullName.value;
            user.emailAddress = emailAddress.value;
            user.contactNumber = Number(contactNumber.value);
            user.postCode = Number(postCode.value);
            user.Password = Password.value;

            users.push(user);
            console.log(users);
            console.log(users.length);

            registerForm.innerHTML = 'Thank you for joining!';
            registerForm.style.fontSize = '1.5rem';
            registerForm.style.fontFamily = 'Segoe UI, Tahoma, Geneva, Verdana, sans-serif';
            registerForm.style.textAlign = 'center';
            registerForm.style.marginTop = '50%';

            users[count] = user;
            count = count + 1;
        }
Ahmad ul hoq Nadim
2022-06-24

<form> 绑定到“submit”事件:

form.addEventListener("submit", (e) => {//...

此外,

  • 如果有 .length ,则实际上不需要计数。
  • FormData() user 对象有点相似(不过您的方法似乎更简单)。
  • 使用的语法来自 HTMLFormElement 接口。
  • 不要将电话和邮政编码值转换为数字,除非您打算排序他们。
  • .phone type 更改为 tel
const form = document.forms.join;
const IO = form.elements;

const id = IO.username;
const name = IO.fullname;
const email = IO.email;
const cell = IO.phone;
const zip = IO.postcode;
const pass = IO.password;

let users = [];
let user = {};

form.addEventListener("submit", (e) => {
  e.preventDefault();

  user.id = id.value;
  user.name = name.value;
  user.email = email.value;
  user.cell = cell.value;
  user.zip = zip.value;
  user.pass = pass.value;

  users.push(user);
  console.log(users);
  console.log(users.length);

  form.innerHTML = 'Thank you for joining!';
  form.style.fontSize = '1.5rem';
  form.style.fontFamily = 'Segoe UI, Tahoma, Geneva, Verdana, sans-serif';
  form.style.textAlign = 'center';
  form.style.marginTop = '50%';

});
<form id="join">

  <ul>
    <li><input type="text" name="username" class="username" placeholder="Username" required></li>

    <li><input type="text" name="fullname" class="fullname" placeholder="Full Name" required></li>

    <li><input type="email" name="email" class="email" placeholder="Email Address" pattern=".+@gmail\.com" required></li>

    <li><input type="tel" name="phone" class="phone" placeholder="Phone Number" required></li>

    <li><input type="text" name="postcode" class="postcode" placeholder="Post Code" required></li>

    <li><input type="password" name="password" class="password" placeholder="Enter a password" required></li>
  </ul>
  <input type="submit">
</form>
zer00ne
2022-06-24