We use cookies to enhance your experience on the site
CodeWorlds

Form Events

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.

Handling Forms

1const ticketBookingForm = document.getElementById('booking-form');
2const emailInput = document.getElementById('email');
3const phoneInput = document.getElementById('phone');
4const ticketTypeSelect = document.getElementById('ticket-type');
5
6// Submit - form submission
7ticketBookingForm.addEventListener('submit', (e) => {
8  e.preventDefault();
9  
10  const formData = new FormData(ticketBookingForm);
11  const bookingData = {
12    name: formData.get('name'),
13    email: formData.get('email'),
14    phone: formData.get('phone'),
15    ticketType: formData.get('ticket-type'),
16    visitDate: formData.get('visit-date'),
17    guestCount: parseInt(formData.get('guest-count'))
18  };
19  
20  if (validateBookingData(bookingData)) {
21    submitBooking(bookingData);
22  }
23});
24
25// Input - field value change
26emailInput.addEventListener('input', (e) => {
27  const email = e.target.value;
28  if (isValidEmail(email)) {
29    e.target.classList.remove('invalid');
30    e.target.classList.add('valid');
31  } else {
32    e.target.classList.remove('valid');
33    e.target.classList.add('invalid');
34  }
35});
36
37// Change - value changed (triggered after leaving the field)
38ticketTypeSelect.addEventListener('change', (e) => {
39  const selectedType = e.target.value;
40  updateTicketPrice(selectedType);
41  showTicketTypeInfo(selectedType);
42});

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."

1const submitBtn = document.getElementById('submit-btn');
2
3// Traditional function - this points to the element with the listener
4submitBtn.addEventListener('click', function(event) {
5  console.log(this);          // <button id="submit-btn">
6  console.log(this === event.currentTarget); // true
7  console.log(event.target);  // the element that was actually clicked
8
9  // this is the element with the listener, event.target is the clicked element
10  this.textContent = 'Submitted!';
11  this.disabled = true;
12});
13
14// Arrow function - this does NOT point to the element!
15submitBtn.addEventListener('click', (event) => {
16  console.log(this); // window (or undefined in strict mode)
17  // Arrow functions don't have their own this
18  // Use event.currentTarget instead of this
19  event.currentTarget.textContent = 'Submitted!';
20});

"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
."

Go to CodeWorlds