Search code examples
typescriptformspreventdefault

Why does my page keep reloading despite event.preventDefault ()?


Whenever I want to call my functions either with the button or with Enter, the page reloads even though I have set event.preventDefault (). How can I stop my page from reloading?

A part of my HTML:

<form>
        <input id="vornameInput">
        <button id="vornameButton">Submit</button>
 </form>

A part of my Typescript:

let vornameInputfield: HTMLInputElement;
let vornameButton: HTMLButtonElement;
let personenListe: PersonenListe;
let ulListe: HTMLUListElement;

document.addEventListener('DOMContentloaded', function () {
    vornameInputfield = <HTMLInputElement>document.getElementById('vornameInput');
    vornameButton = <HTMLButtonElement>document.getElementById('vornameButton');
    ulListe = <HTMLUListElement>document.getElementById('personenListe');
    personenListe = new PersonenListe();


    vornameButton.addEventListener('click', function (event: MouseEvent) {

        let vorname: string = vornameInputfield.value;
        event.preventDefault();

        if (vorname.trim().length !== 0) {
            personenListe.addPerson(vorname);
            vornameInputfield.value = "";
        }
    })

    const ENTER_KEY = 13
    vornameInputfield.addEventListener('keyup', function (event: KeyboardEvent) {
        event.preventDefault();

        if (event.keyCode === ENTER_KEY) {
            let vorname: string = vornameInputfield.value;
            if (vorname.trim().length !== 0) {
                personenListe.addPerson(vorname);
                vornameInputfield.value = "";

            }
        }
    })

})


Solution

  • That's because you're preventing the default events for click and keyup, but what you want to prevent is the default submit event on the form.

    Add an id to the form as you did for the input and button:

    <form id="vornameForm">
            <input id="vornameInput">
            <button id="vornameButton">Submit</button>
     </form>
    

    Then, get it with the code and prevent the default submit event on the form:

    let vornameForm: HTMLFormElement;
    //...
    
    document.addEventListener('DOMContentloaded', function () {
        vornameForm = <HTMLFormElement>document.getElementById('vornameForm');
        //...
    
        vornameForm.addEventListener('submit', function(event: Event) {
            event.preventDefault();
        }
    
        //...
    })