0

I tried to use event.preventDefault() to prevent the page from refreshing but the page still refreshes and the alert will not show. However, when I put the same code into JS Fiddle, the code works fine. What's the issue???

const searchForm = document.getElementById("searchForm");

searchForm.addEventListener('submit', function(event) {
  var topic = document.getElementById("topicSearch").value;
  alert(topic);
  event.preventDefault();
});
<form id="searchForm">
  <input id="topicSearch">
  <button type="submit">Search</button>
</form>
Andy
  • 61,948
  • 13
  • 68
  • 95
  • 1
    Most likely the event is not attached to the form in your page, you're trying to attach it before the form exists. Hit F12 and see if there's an error message in the console. – Teemu Nov 22 '21 at 06:49
  • 1
    Is your ` – Sebastian Simon Nov 22 '21 at 06:49

1 Answers1

-1

you can try this one.

document.addEventListener('readystatechange', function() {
  if(document.readyState == 'complete') {
    const searchForm = document.getElementById("searchForm");

    searchForm.addEventListener('submit', function(event) {
      var topic = document.getElementById("topicSearch").value;
      alert(topic);
      event.preventDefault();
    });
  }
})
<form id="searchForm">
  <input id="topicSearch">
  <button type="submit">Search</button>
</form>
Sean Kumar
  • 26
  • 4
  • Thank you @SebastianSimon I also agree, that will work there is one more we can move the script to the bottom before

    that also will work, I did this because this will work every time once the DOM is fully loaded that's what I think

    – Sean Kumar Nov 22 '21 at 07:30