Friday, 7 September 2018

Javascript/Typescript - Prevent form from resetting on submit

I have a simple typescript class and a want to show the input results on submit. Even though this question is already asked, event.preventDefault() is not working. Maybe you can give me some hints?

class LoginPanel {

    public appDiv: HTMLElement = document.getElementById('app');

    constructor() {
        this.setForm();
        let btn = document.getElementById('loginButton');
        btn.addEventListener('submit', (event) => {event.preventDefault(); this.submitForm()});
    }

    public setForm(): void {
        this.appDiv.innerHTML = `<form id="loginForm" class="form-signin mt-5">
      <div class="text-center">
      <h1 class="h3 mb-3 font-weight-normal">Please sign in</h1>
      </div>
      <label for="inputEmail" class="sr-only">Email address</label>
      <input type="email" id="inputEmail" class="form-control" placeholder="Email address" required="" autofocus="">
      <label for="inputPassword" class="sr-only">Password</label>
      <input type="password" id="inputPassword" class="form-control mt-1" placeholder="Password" required="">
      <button id="loginButton" class="btn btn-lg btn-primary btn-block" type="submit">Sign in</button>
    </form>
    `;
    }

    public submitForm(): void {
        const elementFirst: HTMLElement = document.createElement('pre');
        const elementSecond: HTMLElement = document.createElement('pre');

        elementFirst.innerHTML = 'email: ' + document.getElementById('loginForm')[0].value;
        document.getElementById('loginForm').appendChild(elementFirst);

        elementSecond.innerHTML = 'password: ' + document.getElementById('loginForm')[1].value;
        document.getElementById('loginForm').appendChild(elementSecond);
    }

}

new LoginPanel();



from Javascript/Typescript - Prevent form from resetting on submit

No comments:

Post a Comment