I am encountering a problem with validating my form using JavaScript

I've been working on a project where I'm developing a website using JavaScript, HTML, and CSS to search for movies and purchase tickets. While the basic functionalities are working fine, I'm encountering some challenges with form validation.

Here's how the site functions:

  1. Users search for a movie title and poster image, which is retrieved from the omdb API
  2. Users input their details in a form (name, email, ticket quantity)
  3. Users click "order tickets" and see a thank you message, along with the order history being displayed

If a user fails to enter their name, email, or ticket quantity, the order should not be added to the history. Additionally, even if the page reloads unexpectedly, the order history should persist.

To ensure users provide the necessary information, I have included the required attribute in each field as shown below:

<section id="Order-Form" style="display: none;">
  <h2>Order your tickets</h2>
  <ul>
      <li>
          <label for="User">Please enter your name:</label>
          <input type="text" id="User" value="" required>
      </li>
      <li>
          <label for="Email">Please enter your E-mail address:</label>
          <input type="email" id="Email" value="" required>
      </li>
      <li>
          <label for="Ticket-Amount">Amount of tickets: (You can order a maximum of 8 tickets)</label>
          <input type="number" id="Ticket-Amount" value="" min="1" max="8" required>
      </li>

Below is the code snippet for my page

...

My goal is to enforce completion of the "user, email, and ticket amount" fields while limiting ticket orders to a maximum of 8. I suspect that the lack of logic in the function hookupEventHandlers() may be causing this issue. Can someone assist me in integrating more validation logic into it?

Answer №1

It appears that there are a few issues that need to be addressed.

Concerns with Click Events

Having three click events attached to the same button is not ideal.

document.getElementById("Place-Order").addEventListener("click", processForm);
document.getElementById("Place-Order").addEventListener("click", displayThankYouMessage);
document.getElementById("Place-Order").addEventListener("click", showOrderHistory);

Instead of multiple click event listeners, consider having one function like processForm handle the actions sequentially.

function processForm(){
  // logic implementation...
  
  if(isValid){
    displayThankYouMessage();
    showOrderHistory();
  }
}

If you absolutely require all three functions to be executed simultaneously on button click, it's better to combine them under a single event handler:

document.getElementById("Place-Order").addEventListener("click", ()=>{
  processForm();
  displayThankYouMessage();
  showOrderHistory()
});

Optimizing Form Usage

The <form> element should be utilized properly. Use the native form submit event for field validation without the need for JavaScript handling.

<form>
  <input type="text" required>
  
  <button type="submit">Submit that form!</button>
</form>

Add an event listener for the form's submit event instead of binding to the button's click event for automatic validation upon submission.

document.getElementById("My-Form").addEventListener("submit", (submitEvent)=>{
  console.log(submitEvent)
});
<form id="My-Form">
  <h2>Order your tickets</h2>
  <ul>
    <li>
        <label for="User">Please enter your name:</label>
        <input type="text" id="User" value="" required>
    </li>
    <li>
        <label for="Email">Please enter your E-mail address:</label>
        <input type="email" id="Email" value="" required>
    </li>
    <li>
        <label for="Ticket-Amount">Amount of tickets: (You can order a maximum of 8 tickets</label>
        <input type="number" id="Ticket-Amount" value="" min="1" max="8" required>
    </li>
  </ul>
  
  <button type="submit">Submit that form!</button>
</form>

The browser's built-in validation features cover required fields, email validation, and number input constraints automatically. Custom validations can be implemented as needed, but those details could be addressed separately.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Ensure that containers of varying sizes are arranged properly using Bootstrap

I run a blog site that utilizes bootstrap for creating and posting content on an index page. Given the varying thumbnail sizes, there may be differences in length unless a standard image size is adopted. Here's how it would appear with a standard si ...

Enhance every ajax post request using jQuery

I want to include a csrf token from cookies in all my ajax posts. I've attempted the following: $.ajaxPrefilter(function(options, originalOptions, jqXHR) { if(options.type.toUpperCase() === "POST") options.data = options.data || {}; ...

`Next.js project experiencing issues with scroll trigger functionality`

I've been working on a gsap animation with a scroll trigger, and while the animation itself functions fine, it's not triggering as expected. The AnimationEffect code involves using gsap and scrolltrigger to create the animation. The Hero section ...

Utilizing HTML5 to target and conceal an entire column dynamically with the help of JavaScript/jQuery

If I need to hide an entire column (consisting of one TH and multiple TDs) using HTML5, what is the best approach? In the past, I would use a "Name" attribute to identify all the columns I wanted to hide at once by iterating over document.GetElementsByNam ...

Do you believe that using bower to install HTML5Boilerplate is a beneficial decision?

Is it recommended to use HTML5 Boilerplate with Bower for installation? What steps should one take afterwards, considering that it has its own directory structure for CSS and JavaScript, leading everything to be contained under bower_components/html5boil ...

"Function.click operates successfully when no arguments are given, but encounters issues when arguments are supplied

I had a function that was functioning correctly: $('#buttFurniture').click(onFilterCLick); However, when I decided to pass arguments to the function, it stopped working: $('#buttFurniture').click(onFilterCLick(arrOutput, arrFurniture ...

Guide on programmatically redirecting a user to a different route

I am currently working on a VueJS 3 application using Quasar, and I am facing difficulties with programmatically utilizing the Router. The issue can be summarized as follows: 1. The Challenge When attempting to navigate the User to a different route, onl ...

Angular dependency injection function

What is the best placement for the common handleError and handleSuccess functions? These functions are commonly used by every service. Where should these functions be placed? Should they be global functions injected as dependencies? (function () { "u ...

Using jQuery UI Tabs to Dynamically Select a Tab Based on a Link

Recently, I have been exploring the idea of using a script to open a specific tab: $('.tofour').click(function() { // bind click event to link $tabs.tabs('select', 3); // switch to third tab return false; }); However, my dilem ...

Is there a way for app.use to identify and match requests that begin with the same path?

Given that app.use() responds to any path that starts with /, why does the request localhost:3000/foo match the second method instead of the first? app.use("/",express.static('public'), function(req,res,next) { console.log(& ...

Invoking Ajax within a for loop

for (var i = 0; i < 5; i++) { using (x = new XMLHttpRequest()) sendRequest("GET","d.php?id=" + i), checkResponse(null), updateStatus = function() { if (x.state == 4 && x.responseCode == 200) notifyUser(i); } } My goal now is to e ...

Retrieve values from the same row using JQuery

<tr> <td style="display:none;"> 62 </td> <td> <span style="color:Blue; cursor:pointer;" id="editLink">Edit</span> | ...

Navigation links transforming hues unpredictably

After creating a navigation list for a client using the [Oswald]() font-face, an issue arose when the user scrolled over the links. Instead of a navigation arrow popping up as intended, the links turned orange upon hovering. Despite removing all javascript ...

Ways to center items in a row-oriented collection

When dealing with a horizontal list, the issue arises when the first element is larger than the others. This can lead to a layout that looks like this. Is there a way to vertically align the other elements without changing their size? I am aware of manual ...

A guide to personalizing the woocommerce 'best-selling items' widget

WooCommerce widgets are great, but I'm struggling to customize the styling. Can anyone lend a hand? ...

When opening a dialog at the bottom of the page, the window will automatically scroll to the top

I'm encountering an issue with a page that has a width exceeding 100% (2000px). Whenever I click to display a dialog from a button located at the end of the horizontal page, the window automatically scrolls back to the beginning of the page before sho ...

Guide to using get() and res.sendFile() function to redirect webpages

Why is the page not redirecting properly? In my index.html file, I have this script: $.get( "/loginPage", function( data ) {}); The purpose of this script is to check if a user is logged in. If they are, it should redirect them to the lobbyPage. This is ...

Service in AngularJS designed specifically for storing and managing SEO metadata

I stumbled upon a tutorial that introduced me to using a service for dynamic SEO metadata here: However, I encountered an issue - It seems like the service is not accessible outside of the controller's view. <div ui-view></div> Here is t ...

How can I trigger a function again when an anchor link is clicked and received via Ajax?

I am currently working on creating a unique page transition effect using jQuery and Ajax. This is what I have so far: $(".transitionLink").on("click", function (event) { event.preventDefault(); var href = $(this).attr("href"); window.histor ...

The image area mapping is displaying infinity instead of a specific numerical value

Currently, I am utilizing the library react-image-mapper to incorporate clickable areas on an image. However, upon the initial page load, the generated HTML displays the area with a value of infinity, rendering the image unclickable. It is only after a pag ...