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