首页 > 解决方案 > addEventListener 在表单上不起作用 - vanilla JS

问题描述

我在制作用于简单 Rails 项目的表单时遇到问题。

基本思想是从表单中获取名称和日期,然后使用 JS 在同一页面上重新使用它们。我稍后会处理这些信息,确定今天是否是您的生日,以及距离您的下一个生日还有多少天。

在 localhost 中首次加载页面时,JS 似乎没有正确加载。它没有找到表格。我在控制台中有这条消息,指的是表单 ID:

未捕获的类型错误:无法读取 null 的属性“addEventListener”

如果我第一次填写表格,什么都不会发生。如果我只是刷新页面,或者再次提交表单,表单和 JS 工作正常。我的 URI 更改为 localhost:3000/page 到 localhost:3000/page?。我想知道为什么,我已经在 J​​S 上设置了阻止默认值。

我试图在 JS 脚本的开头加上一个条件,如果表单存在,然后做你的事情。我没有第一个控制台错误,但脚本在第一页加载时仍然不起作用。

感谢您的建议。

表单的 HTML 代码:

    <div class="js-form">
        <form id= "new_test_form">
            <div class="mb-3">
                <label for="username" class="form-label"> Your Name</label>
                <input type="text" class="form-control" id="username">
            </div>
            <div class="mb-3">
                <label for="dateinput" class="form-label">Your birth date</label>
                <input type="date" class="form-control" id="dateinput">
            </div>
            <button type="submit" class="btn btn-primary">Submit</button>
        </form>
    </div>
    <div class="results">
    Here will be displayed the results
    </div>

和JS

console.log('Hello from My bdtest')

const form2 = document.querySelector("#new_test_form");
const result = document.querySelector(".results"); // CSS id selector

if (form2) {
  form2.addEventListener("submit", (event) => {
  event.preventDefault();
  const fn_form = document.querySelector("#username").value
  const age_form = document.querySelector("#dateinput").value
  const nd = new Date(age_form)
  console.log(fn_form);
  console.log(age_form);
  console.log(nd.toDateString());
  result.insertAdjacentHTML("beforeend", `<p> Your Name is <strong>${fn_form}</strong></p>` );
  result.insertAdjacentHTML("beforeend", `Your date of birth is ${age_form}` );
  });
}

标签: javascriptruby-on-rails

解决方案


JS 在您的 HTML 之前加载吗?所以JS找不到#new_test_form。尝试将您的 JS 代码包装在:

document.addEventListener("DOMContentLoaded", function(event) { 
  //do work
});

推荐阅读