簡體   English   中英

addEventListener 在表單上不起作用 - vanilla JS

[英]addEventListener not working on a form - vanilla JS

我在制作用於簡單 Rails 項目的表單時遇到問題。

基本思想是從表單中獲取名稱和日期,然后使用 JS 在同一頁面上重復使用它們。 我稍后會處理這些信息,確定今天是否是您的生日,以及距離您的下一個生日還有多少天。

在 localhost 中首次加載頁面時,JS 似乎沒有正確加載。 它沒有找到表格。 我在控制台中有這條消息,指的是表單 ID:

未捕獲的類型錯誤:無法讀取 null 的屬性“addEventListener”

如果我第一次填寫表格,什么都不會發生。 如果我只是刷新頁面,或者再次提交表單,表單和 JS 工作正常。 我的 URI 更改為 localhost:3000/page 到 localhost:3000/page?。 我想知道為什么,我已經在 JS 上設置了阻止默認值。

我試圖在 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}` );
  });
}

JS 是否在您的 HTML 之前加載? 所以JS找不到#new_test_form。 嘗試將您的 JS 代碼包裝在:

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

感謝@tihu 的貢獻。 我讓我朝着正確的方向前進。 挖掘之后,我發現了一個更具體的事件來聽:

    document.addEventListener("turbolinks:load", (event) => {
      console.log("Turbolinks turboed ✌");
    });

現在表單一直有效,即使在第一頁渲染時也是如此。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM