Create Form Using Class – React Form

TypeScript Form preventDefault on Submit

<div id="app"></div>


class LoginPanel {

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

    constructor() {
        this.setForm();
        const form = document.getElementById('loginForm');
        form.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();

Reference

Class Form

Leave a Reply

Your email address will not be published. Required fields are marked *