JavaScript and TypeScript course Β· Module 8: Events and the DOM

Form Events

5 min read Β·

Forms in Jurassic Park are used for guest registration, staff management, and security systems. Similarly, in web applications, forms are key for interacting with users.

Imagine a booking form for a tour of the T-Rex enclosure. Without JavaScript, clicking "Send" makes the browser reload the whole page, and the guest only finds out about a typo in their email address when the confirmation never arrives. Form events let you take over this process and react before anything leaves the browser.

Handling Forms

The most important signal is submit. A form sends it when the guest clicks the submit button or presses Enter in a text field. We attach the listener to the form itself, not to the button, so that we catch both.

const ticketBookingForm = document.getElementById('booking-form');
const emailInput = document.getElementById('email');
const phoneInput = document.getElementById('phone');
const ticketTypeSelect = document.getElementById('ticket-type');

// Submit - form submission
ticketBookingForm.addEventListener('submit', (e) => {
  e.preventDefault();

  const formData = new FormData(ticketBookingForm);
  const bookingData = {
    name: formData.get('name'),
    email: formData.get('email'),
    phone: formData.get('phone'),
    ticketType: formData.get('ticket-type'),
    visitDate: formData.get('visit-date'),
    guestCount: parseInt(formData.get('guest-count'))
  };

  if (validateBookingData(bookingData)) {
    submitBooking(bookingData);
  }
});

Handling a submission always has four phases in the same order. First we intercept the submit event, then we call preventDefault() to stop the default submission and page reload, next we validate the data, and finally we send it ourselves. The FormData object collects field values by their name attributes, and text and number fields hand them over as text, which is why the guest count goes through parseInt().

You can do the sending with the fetch() function you know from the lesson on asynchronous programming. Here is a sample version of submitBooking() that sends the booking as JSON.

async function submitBooking(bookingData) {
  const response = await fetch('/api/bookings', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(bookingData)
  });

  if (!response.ok) {
    console.error('Booking rejected:', response.status);
    return;
  }
  console.log('Booking accepted!');
}

The page never reloads, and the guest stays on the form. Remember that fetch() throws an error only when there is a network problem. A response with a 400 or 500 code is a successful delivery as far as it is concerned, so we check response.ok ourselves.

Real-Time Validation

The input event fires on every change of the field's value: every typed character, paste, or deletion. Before we use it, we need a function that checks the email address.

function isValidEmail(email) {
  return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
}

It's a simplified guard: it requires an @ sign and a dot in the domain, but it doesn't check whether the mailbox exists. Now we connect it to the field so that the CSS class changes as the guest types.

// Input - field value change
emailInput.addEventListener('input', (e) => {
  const email = e.target.value;
  if (isValidEmail(email)) {
    e.target.classList.remove('invalid');
    e.target.classList.add('valid');
  } else {
    e.target.classList.remove('valid');
    e.target.classList.add('invalid');
  }
});

The guest sees a red or green border while typing, and the field's value stays untouched, because we only change its class.

The change Event

The change event fires less often, only once the change is committed. For a <select> list this happens right after choosing an option, and for a text field only after leaving it.

// Change - committed change (select: right after choosing, text field: after leaving it)
ticketTypeSelect.addEventListener('change', (e) => {
  const selectedType = e.target.value;
  updateTicketPrice(selectedType);
  showTicketTypeInfo(selectedType);
});

change is a perfect fit for recalculating the ticket price, because we react to the guest's decision rather than to every moment of hesitation. My rule: input for live hints, change for reacting to a choice, and submit for the final check. Leave the simplest rules, like required or type="email", to HTML attributes. The browser will block an invalid form on its own and won't even send submit in that case.

The this Context in Event Handlers

An important aspect of event handlers is the this context. In a traditional function (function expression), this refers to the element on which the event listener was registered - that is, the element to which the handler is "attached."

const submitBtn = document.getElementById('submit-btn');

// Traditional function - this points to the element with the listener
submitBtn.addEventListener('click', function(event) {
  console.log(this);          // <button id="submit-btn">
  console.log(this === event.currentTarget); // true
  console.log(event.target);  // the element that was actually clicked

  // this is the element with the listener, event.target is the clicked element
  this.textContent = 'Submitted!';
  this.disabled = true;
});

Here this equals event.currentTarget, which is why the button can change its own text and disable itself. event.target points to the element that was actually clicked, and for a button with plain text it's the same element. An arrow function behaves differently.

// Arrow function - this does NOT point to the element!
submitBtn.addEventListener('click', (event) => {
  console.log(this); // this from the surrounding code, e.g. window (in an ES module: undefined)
  // Arrow functions don't have their own this
  // Use event.currentTarget instead of this
  event.currentTarget.textContent = 'Submitted!';
});

An arrow function has no this of its own, so it takes it from the surrounding code. At the top level of a regular script that will be window, and in an ES module the value undefined. You definitely won't get the button here, which is why arrow functions reach for event.currentTarget.

"Remember," Ray warns, "arrow functions don't have their own this. If you need to refer to the element via this, use traditional functions. If you prefer arrow functions, use event.currentTarget."

I go with arrow functions and event.currentTarget, because such code works the same no matter where you move it. In the sandbox below, a tour booking form awaits you with all three events, plus focus and blur, which fire when a field gains and loses focus. In the next lesson you'll learn to clean up after listeners when a form disappears from the page.

Remember: a form is the gate to the park, and submit with preventDefault() is the guard who checks the pass before anyone goes any further.

Code for this lesson: index.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Form events - Tour booking</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: linear-gradient(135deg, #2c3e50 0%, #34495e 100%);
            padding: 20px;
            color: white;
            min-height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .form-container {
            max-width: 600px;
            width: 100%;
            background: rgba(0, 0, 0, 0.8);
            border-radius: 15px;
            padding: 40px;
            box-shadow: 0 20px 60px rgba(0, 0, 0, 0.5);
        }

        h1 {
            text-align: center;
            margin-bottom: 10px;
            color: #ecf0f1;
        }

        .subtitle {
            text-align: center;
            color: #bdc3c7;
            margin-bottom: 30px;
        }

        .form-group {
            margin-bottom: 25px;
        }

        label {
            display: block;
            margin-bottom: 8px;
            color: #ecf0f1;
            font-weight: 500;
        }

        .required {
            color: #e74c3c;
        }

        input, select, textarea {
            width: 100%;
            padding: 12px 15px;
            border: 2px solid #34495e;
            border-radius: 8px;
            background: rgba(255, 255, 255, 0.1);
            color: white;
            font-size: 16px;
            transition: all 0.3s ease;
        }

        input:focus, select:focus, textarea:focus {
            outline: none;
            border-color: #3498db;
            background: rgba(255, 255, 255, 0.15);
        }

        input.valid {
            border-color: #27ae60;
            background: rgba(39, 174, 96, 0.1);
        }

        input.invalid {
            border-color: #e74c3c;
            background: rgba(231, 76, 60, 0.1);
        }

        .error-message {
            color: #e74c3c;
            font-size: 14px;
            margin-top: 5px;
            display: none;
        }

        .input-hint {
            color: #95a5a6;
            font-size: 13px;
            margin-top: 5px;
        }

        .char-counter {
            text-align: right;
            color: #95a5a6;
            font-size: 12px;
            margin-top: 5px;
        }

        .submit-btn {
            width: 100%;
            padding: 15px;
            background: linear-gradient(45deg, #27ae60, #2ecc71);
            color: white;
            border: none;
            border-radius: 8px;
            font-size: 18px;
            font-weight: bold;
            cursor: pointer;
            transition: all 0.3s ease;
            margin-top: 20px;
        }

        .submit-btn:hover:not(:disabled) {
            transform: translateY(-2px);
            box-shadow: 0 10px 25px rgba(39, 174, 96, 0.3);
        }

        .submit-btn:disabled {
            background: #7f8c8d;
            cursor: not-allowed;
        }

        .success-message {
            background: linear-gradient(45deg, #27ae60, #2ecc71);
            color: white;
            padding: 20px;
            border-radius: 10px;
            text-align: center;
            display: none;
            animation: slideIn 0.5s ease;
        }

        @keyframes slideIn {
            from {
                opacity: 0;
                transform: translateY(-20px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }

        .price-info {
            background: rgba(52, 152, 219, 0.2);
            border: 1px solid #3498db;
            border-radius: 8px;
            padding: 15px;
            margin: 20px 0;
            text-align: center;
        }

        .price-value {
            font-size: 32px;
            font-weight: bold;
            color: #3498db;
        }

        .event-log {
            background: rgba(0, 0, 0, 0.6);
            border-radius: 8px;
            padding: 15px;
            margin-top: 20px;
            max-height: 200px;
            overflow-y: auto;
            font-family: 'Courier New', monospace;
            font-size: 12px;
        }

        .log-entry {
            padding: 3px 0;
            border-bottom: 1px solid rgba(255, 255, 255, 0.1);
            color: #95a5a6;
        }
    </style>
</head>
<body>
    <div class="form-container">
        <h1>Tour Booking</h1>
        <p class="subtitle">Jurassic Park - Discover the world of dinosaurs</p>

        <form id="booking-form">
            <div class="form-group">
                <label for="name">Full name <span class="required">*</span></label>
                <input type="text" id="name" name="name" required>
                <div class="error-message" id="name-error">Enter full name (min. 3 characters)</div>
            </div>

            <div class="form-group">
                <label for="email">Email <span class="required">*</span></label>
                <input type="email" id="email" name="email" required>
                <div class="error-message" id="email-error">Enter a valid email address</div>
                <div class="input-hint">We will send reservation confirmation to this address</div>
            </div>

            <div class="form-group">
                <label for="phone">Contact phone <span class="required">*</span></label>
                <input type="tel" id="phone" name="phone" placeholder="+48 123 456 789" required>
                <div class="error-message" id="phone-error">Enter a valid phone number</div>
            </div>

            <div class="form-group">
                <label for="date">Tour date <span class="required">*</span></label>
                <input type="date" id="date" name="date" required>
                <div class="error-message" id="date-error">Choose a future date</div>
            </div>

            <div class="form-group">
                <label for="tour-type">Tour type <span class="required">*</span></label>
                <select id="tour-type" name="tour-type" required>
                    <option value="">Choose a tour type</option>
                    <option value="standard" data-price="150">Standard (2h) - 150 USD</option>
                    <option value="vip" data-price="300">VIP with guide (4h) - 300 USD</option>
                    <option value="night" data-price="250">Night tour (3h) - 250 USD</option>
                    <option value="family" data-price="500">Family (4h, max 4 people) - 500 USD</option>
                </select>
            </div>

            <div class="form-group">
                <label for="guests">Number of guests <span class="required">*</span></label>
                <input type="number" id="guests" name="guests" min="1" max="20" value="1" required>
                <div class="input-hint">Min. 1, max. 20 guests</div>
            </div>

            <div class="form-group">
                <label for="comments">Additional comments</label>
                <textarea id="comments" name="comments" rows="4" maxlength="500"></textarea>
                <div class="char-counter" id="char-counter">0 / 500 characters</div>
            </div>

            <div class="price-info">
                <div style="color: #bdc3c7; margin-bottom: 10px;">Total cost:</div>
                <div class="price-value" id="total-price">0 USD</div>
            </div>

            <button type="submit" class="submit-btn" id="submit-btn" disabled>
                Book a tour
            </button>
        </form>

        <div class="success-message" id="success-message">
            <h2>Booking confirmed!</h2>
            <p>Thank you for your reservation. Details have been sent to the provided email address.</p>
        </div>

        <div class="event-log" id="event-log">
            <strong>Form event log:</strong>
        </div>
    </div>

    <script>
        console.log('Jurassic Park booking system - ONLINE');

        // References to elements
        const form = document.getElementById('booking-form');
        const nameInput = document.getElementById('name');
        const emailInput = document.getElementById('email');
        const phoneInput = document.getElementById('phone');
        const dateInput = document.getElementById('date');
        const tourTypeSelect = document.getElementById('tour-type');
        const guestsInput = document.getElementById('guests');
        const commentsTextarea = document.getElementById('comments');
        const charCounter = document.getElementById('char-counter');
        const totalPriceDisplay = document.getElementById('total-price');
        const submitBtn = document.getElementById('submit-btn');
        const successMessage = document.getElementById('success-message');
        const eventLog = document.getElementById('event-log');

        // Logging function
        function logEvent(message) {
            const entry = document.createElement('div');
            entry.className = 'log-entry';
            entry.textContent = `[${new Date().toLocaleTimeString()}] ${message}`;
            eventLog.appendChild(entry);
            eventLog.scrollTop = eventLog.scrollHeight;
            console.log(message);
        }

        // Validation functions
        function validateName(name) {
            return name.trim().length >= 3;
        }

        function validateEmail(email) {
            const regex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
            return regex.test(email);
        }

        function validatePhone(phone) {
            const cleaned = phone.replace(/\s/g, '');
            return cleaned.length >= 9;
        }

        function validateDate(date) {
            const selected = new Date(date);
            const today = new Date();
            today.setHours(0, 0, 0, 0);
            return selected > today;
        }

        function showError(input, errorId, show) {
            const errorElement = document.getElementById(errorId);
            if (show) {
                errorElement.style.display = 'block';
                input.classList.add('invalid');
                input.classList.remove('valid');
            } else {
                errorElement.style.display = 'none';
                input.classList.remove('invalid');
                input.classList.add('valid');
            }
        }

        function updateTotalPrice() {
            const selectedOption = tourTypeSelect.options[tourTypeSelect.selectedIndex];
            const pricePerPerson = parseInt(selectedOption.dataset.price) || 0;
            const guests = parseInt(guestsInput.value) || 0;
            const total = pricePerPerson * guests;
            totalPriceDisplay.textContent = `${total} USD`;
            logEvent(`Updated price: ${total} USD`);
        }

        function checkFormValidity() {
            const isValid = validateName(nameInput.value) &&
                          validateEmail(emailInput.value) &&
                          validatePhone(phoneInput.value) &&
                          validateDate(dateInput.value) &&
                          tourTypeSelect.value !== '' &&
                          guestsInput.value >= 1;
            submitBtn.disabled = !isValid;
        }

        // INPUT EVENT - real-time validation
        nameInput.addEventListener('input', function(e) {
            const isValid = validateName(e.target.value);
            showError(nameInput, 'name-error', !isValid);
            logEvent(`Typing name: ${e.target.value.length} characters`);
            checkFormValidity();
        });

        emailInput.addEventListener('input', function(e) {
            const isValid = validateEmail(e.target.value);
            showError(emailInput, 'email-error', !isValid);
            logEvent(`Typing email: ${e.target.value}`);
            checkFormValidity();
        });

        phoneInput.addEventListener('input', function(e) {
            const isValid = validatePhone(e.target.value);
            showError(phoneInput, 'phone-error', !isValid);
            checkFormValidity();
        });

        // CHANGE EVENT - value change
        dateInput.addEventListener('change', function(e) {
            const isValid = validateDate(e.target.value);
            showError(dateInput, 'date-error', !isValid);
            logEvent(`Date selected: ${e.target.value}`);
            checkFormValidity();
        });

        tourTypeSelect.addEventListener('change', function(e) {
            const selectedText = e.target.options[e.target.selectedIndex].text;
            logEvent(`Tour type selected: ${selectedText}`);
            updateTotalPrice();
            checkFormValidity();
        });

        guestsInput.addEventListener('change', function(e) {
            logEvent(`Changed number of guests: ${e.target.value}`);
            updateTotalPrice();
        });

        // FOCUS/BLUR EVENTS
        const allInputs = [nameInput, emailInput, phoneInput, dateInput, tourTypeSelect, guestsInput, commentsTextarea];

        allInputs.forEach(input => {
            input.addEventListener('focus', function() {
                logEvent(`Focus on: ${this.name || this.id}`);
            });

            input.addEventListener('blur', function() {
                logEvent(`Blur from: ${this.name || this.id}`);
            });
        });

        // Character counter for the textarea
        commentsTextarea.addEventListener('input', function(e) {
            const length = e.target.value.length;
            const maxLength = e.target.maxLength;
            charCounter.textContent = `${length} / ${maxLength} characters`;

            if (length > maxLength - 50) {
                charCounter.style.color = '#e74c3c';
            } else {
                charCounter.style.color = '#95a5a6';
            }
        });

        // SUBMIT EVENT
        form.addEventListener('submit', function(e) {
            e.preventDefault();

            if (submitBtn.disabled) {
                alert('Form contains errors. Fix them before submitting.');
                return;
            }

            const formData = new FormData(form);
            const data = {
                name: formData.get('name'),
                email: formData.get('email'),
                phone: formData.get('phone'),
                date: formData.get('date'),
                tourType: formData.get('tour-type'),
                guests: formData.get('guests'),
                comments: formData.get('comments') || 'None'
            };

            logEvent(`Submitting form...\nData: ${JSON.stringify(data, null, 2)}`);

            submitBtn.textContent = 'Booking...';
            submitBtn.disabled = true;

            setTimeout(() => {
                form.style.display = 'none';
                successMessage.style.display = 'block';
                logEvent('Reservation successfully registered!');

                console.log('Booking data:', data);

                setTimeout(() => {
                    form.style.display = 'block';
                    successMessage.style.display = 'none';
                    form.reset();
                    submitBtn.textContent = 'Book a tour';
                    totalPriceDisplay.textContent = '0 USD';
                    allInputs.forEach(input => input.classList.remove('valid', 'invalid'));
                    checkFormValidity();
                }, 3000);
            }, 2000);
        });

        // Set minimum date to tomorrow
        const tomorrow = new Date();
        tomorrow.setDate(tomorrow.getDate() + 1);
        dateInput.min = tomorrow.toISOString().split('T')[0];

        logEvent('Reservation system loaded');
    </script>
</body>
</html>

Docs entries used in this lesson

Spotted a mistake in this lesson?

Check yourself

Answer the questions from this lesson. Pick an answer to see right away whether it is correct.

  1. 1. What does 'this' refer to in a traditional event handler function?

  2. 2. What should be done to prevent the default page reload when submitting a form?

Hands-on tasks in the game

  • Code editor

    The index.html file has a #navbar bar, and style.css hides it when it has the hidden class. The script remembers the last scroll position (window.scrollY). Fill in the blanks: ___BLANK1___ is the page scroll event listened to on window, and ___BLANK2___ is the comparison operator that detects scrolling down (the new position is greater than the previous one). The bar should hide when scrolling down and come back when scrolling up.

  • Click in order

    Arrange the code for real-time input validation.

  • Vertical ordering

    Arrange the order of form submit event handling:

  1. QuestionQuiz: Event Context
  2. QuestionQuiz: Form Submit Event
  3. Coding taskExercise: Scroll Events
  4. Click in orderSort: Input Validation
  5. Put in orderForm Event Handling Phases

Useful articles