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.
4
Answers
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.
It seems like your JavaScript event listener is correctly preventing the default form submission behavior. However, the issue might be related to the fact that you’re using a
<button>
inside the form. When you have a<button>
inside a form without specifying thetype
attribute, it defaults to"submit"
, causing the form to submit.In your case, you’re preventing the default behavior, but since the button has the default
type
of"submit"
, it might still be triggering the form submission. To fix this, explicitly set thetype
attribute of your button to"button"
to prevent it from triggering the form submission:html
Now, with
type="button"
, clicking the button won’t trigger the form submission, and your JavaScript code inside theaddLink
function should work as expected.Make sure to check if there are any other scripts or changes in your environment that might be affecting the behavior, as the provided code should prevent the form from being submitted.
The submit event belong to the
<form>
element, not on any other button inside the form !To prevent the refresh just add a onsubmit event condition to your form, like this…
Btw, I answered the same request like 2-3 days ago but some people aren’t researching at all! 🙁