小能豆

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

javascript

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.


阅读 77

收藏
2023-11-29

共1个答案

小能豆

It seems like you’re trying to prevent the default form submission behavior by using event.preventDefault() in your click event handler. However, your button has type="submit", which means it will still submit the form.

Here are a couple of things you can check:

1. Update Button Type:

Change the type attribute of the button to "button" instead of "submit":

<button class="links-add-button button submit-button" type="button">
  <i class="fas fa-plus-square"></i>
</button>

This change will prevent the form from being submitted automatically.

2. Check JavaScript Code:

Make sure that there are no errors or issues in your JavaScript code. If there’s an error in your code, it might prevent the default behavior from being canceled. You can check for errors in the browser’s console.

3. Ensure JavaScript Execution:

Ensure that your JavaScript code is being executed. You can add a console.log statement at the beginning of your addLink function to verify if it’s getting called.

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

  console.log("addLink function called"); // Check if this log appears in the console

  // Rest of your code
}

4. Event Delegation:

If your button is dynamically added to the DOM or if there are other event listeners on parent elements, make sure that event delegation is not interfering.

If none of these suggestions resolve the issue, you might want to provide more context or check for any additional code that might affect the behavior.

2023-11-29