"event.preventDefault();" doesn't work with a submit button

196 views Asked by At

The problem is, when I click on a submit button the page is reloading, preventing the code to work, despite the fact that I have "event.preventDefault();".

HTML:

<form class="links-add-container hidden">
  <input
    type="text"
    class="links-name-input links-input"
    spellcheck="false"
    placeholder="Название ссылки"
  />
  <input
    type="text"
    class="links-link-input links-input"
    spellcheck="false"
    placeholder="Ссылка"
  />
  <button class="links-add-button button submit-button" type="submit">
    <i class="fas fa-plus-square"></i>
  </button>
</form>

JS:

const addLinkButton = document.querySelector(".links-add-button");

addLinkButton.addEventListener("click", addLink);

function addLink(event) {
  event.preventDefault();

  //the actual code. It doesn't work because of the page reload.
}

I've tryed to change type of the button on the "button", but it leads to the other problem. The page doesn't reload but the code doesn't work. When i click on the button nothing happens, even error in the console doesn't appear.

I should add that this is my old code and when I worked with it half a year ago there was no such problem. Most likely I'm missing something obvious, but I don't understand what. Please help.

2

There are 2 answers

1
passingThru On

To prevent the refresh just add a onsubmit event condition to your form, like this...

<form class="links-add-container hidden" onsubmit="return false;">

Btw, I answered the same request like 2-3 days ago but some people aren’t researching at all! :(

1
Danil Yahin On

Changing the type of a button to "button" was actually a working solution. The problem was in some kind of local server stuff. When I fixed it, type="button" was a viable solution. Anyway, thank for help.