Using HTML input checkboxes in conjunction with a JavaScript function

After creating a basic payment form using HTML/CSS/JS, I wanted to implement checks on user inputs using HTML patterns. In addition, I aimed to display a pop-up alert using JS to confirm the form submission only after all necessary inputs are correctly filled and meet the specified patterns. The pop-up should also include the name provided by the user upon completion. However, I encountered an issue where the alert would appear prematurely when submitting incomplete information, displaying the message "Order Completed." How can I ensure that the pop-up alert appears only after all input fields are correctly filled? Below is a snippet of my code:

<!DOCTYPE html>
<html>
<style>

    body {
        border:10px solid black;
        margin-top: 100px;
        margin-bottom: 100px;
        margin-right: 150px;
        margin-left: 150px;
    }

    ... // CSS styles

</style>

<body onload="CreditCard();">
    <form id="Myform">
        <div class="login-page">
            <div class="form">

                ... // Form elements and fields

                <input type="submit" value="Submit" onclick="confirmed();">
                <input type="button" onclick="reset()" value="Reset form">

            </div>
        </div>
    </form>

    <script>
        function CreditCard() {
            ... // Logic for showing/hiding credit card details based on payment method
        }

        function reset() {
            ... // Function to reset the form
        }

        function confirmed() {
            ... // Function to display confirmation alert with user's name
        }

        function terms() {
            ... // Additional functionality or logic related to terms agreement
        }
    </script>

</body>

</html>

Please focus on ensuring that the pop-up alert in the `confirmed()` function appears only after all required user inputs are correctly filled.

Answer №1

When you press submit, the submit method is executed. Before the submit method can be executed, it must wait for the confirm method to run first. To access the attribute in your JavaScript code, you can use an id.

document.getElementById('submit-form').submit(function(ev) {
    ev.preventDefault(); // prevent the form from submitting
    confirmed();
    this.submit(); // Proceed with submission if confirmed
});
<input id="submit-form" type="submit" value="Submit">

Answer №2

In order to avoid the form submission, it is necessary to modify the `onclick` attribute.

<input type="submit" value="Submit" onclick="return confirmed();">

Additionally, your function should return either true or false based on your form validation requirements.

Answer №3

  1. It is important to listen for the submit event instead of onclick
  2. Relying solely on client-side validation may offer a good user experience, but it is essential not to fully trust the client
  3. HTML5 offers validation options through the required and pattern attributes in forms
window.addEventListener('load', function () {
    document.getElementById('example-submit').addEventListener('submit', function () {
        alert('done');
    });
});
input:invalid {border: 1px solid red;}
input:valid {border: 1px solid green;}
<form action="?" method="post">
  <input type="text" id="expire-year" required pattern="20[123]\d" placeholder="YYYY" />
  <input type="text" id="expire-month" required pattern="0?[1-9]|1[012]" placeholder="MM" />
  <input type="text" id="expire-day" required pattern="0?[1-9]|2\d|3[01]" placeholder="DD" />
  <input type="submit" id="example-submit" />
</form>

Additional Tips

  • When naming objects, consider using camel case such as creditCard instead of CreditCard
  • To receive quality answers, simplify your code to the essential components, unnecessary HTML can be omitted
  • A live snippet was not used due to limitations with submitting forms within embedded iframes on SO :)

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

Angular 7 three-dimensional model display technology

Looking for advice on creating a 3D model viewer within an Angular 7 project. Currently using the model-viewer web component in JavaScript with success. How can I replicate this functionality and viewer within my Angular 7 application? ...

Is there a way to set the background of a HTML5 page as an image with a clickable link?

Lately, I've been working on a webpage dedicated to educating people about Mars. I wanted to spice things up by using an image as the background for my HTML5 page instead of the usual plain white color. However, just inserting a .jpg link didn't ...

What is the best way to iterate through two arrays without disrupting the sequence of displayed elements?

I am currently working on developing a chat-bot that includes the functionality of sending and receiving voice audio. To achieve this, I have implemented two separate array states: one for rendering text messages and another for rendering audio messages. I ...

Transforming data from a singular object into an array containing multiple objects with key-value pairs

Looking for assistance with converting data from a single object in JSON format to another format. Here is the initial data: var originalData = { "1": "alpha", "2": "beta", "3": "ceta" } The desired format is as follows: var convertedData = ...

Protection of Angular expressions

I have been following the PhoneCat tutorial for AngularJS and found it very helpful up until step 6 where links are generated dynamically from angular expressions: http://localhost:8000/app/{{phone.imageUrl}} Although the tutorial mentions that ngSrc pre ...

Retrieve the title of a webpage using cheerio

I am attempting to extract the title tag of a URL using cheerio, but I keep receiving empty string values. Here is my code snippet: app.get('/scrape', function(req, res){ url = 'http://nrabinowitz.github.io/pjscrape/'; reques ...

What is the best way to reload scripts each time a component is mounted?

My jQuery scripts include animation effects that need to be refreshed whenever something new is rendered on the page. However, I am facing an issue where the jQuery scripts are not being refreshed as needed. Below is my router configuration: export defau ...

Unveiling the secrets of extracting element content using JavaScript (with JQuery) from an HTML object

I have written the code below to access the page "JQueryPage.aspx" and retrieve data from it using jQuery: <script type="text/javascript> $.get ( "JQueryPage.aspx", function(data) { alert("Data Loaded: " + data); ...

Guide on using jQuery to incrementally cycle through an array using a button

I am facing an issue with iterating through an array of objects using a button. The iteration is skipping 2 on each click instead of moving to the very next record. Can someone help me troubleshoot this problem? Or suggest a better approach to iterate thro ...

Establishing a constant for a JavaScript class method

Although this question may seem basic, I am struggling to grasp how this code works and felt the need to seek clarification here. Take a look at this example of a simple React component: const title = React.createElement( 'h1', {id: &apo ...

Interactive form control for location details including country, state, district, and town

I am struggling with adding dynamic form controls on dropdown change. I have been able to add them, but encountered an error preventing me from retrieving the value in 'formName.value'. The specific error message states: "Error: There is no Form ...

What could be causing this `even` function to malfunction when utilizing getElementById?

Need assistance with utilizing document.getElementById? Let's take a look at this code snippet: function even() for (i = 0; i < 10; i++) { if (i % 2 == 0) { alert(i); } } document.getElementById("even").innerHTML = i + &apos ...

Unable to retrieve HTTP call response during debugging, although it is visible in the browser

When I send an HTTP request to create a record, I am able to see the added record id in the Network section of browsers like Chrome and Firefox. However, when I try to debug the code and retrieve the same id value, I encounter difficulties. I have tried us ...

`vue.js: li element tag numbers not displaying correctly`

Issue with Number list not displaying correctly using Vue.js I have tried sending it like this. Is there a fix for this problem? This is the code snippet I used to output in Vue.js: p(v-html="selectedProduct.description") Snapsho ...

Issue with host-context scss rules not appearing in final production version

I am facing an issue in my Angular project where the scss rules that define how components should look when within the context of another component are not being applied when I build for production and put it live. Here is an example: :host-context(my-tabl ...

Updating items within a nested list in Redux can be achieved by carefully managing the state and implementing actions to add or remove

My current state is set up like this: Fruits: { 34: { FruitsID: 34, FruitsList:{apple, pineapple, banana} } } I want to update my fruit list by adding 'peach' and 'pear', while also removing 'apple&apos ...

Displaying HTML with AngularJS dynamic data-binding

Here is a sample view: <div ng-show=""> <div style='background-color: #13a4d6; border-color: #0F82A8'> {{headerdescription}} <div style='float: right'>{{price}} $</div> </div> <div style=&apos ...

An easy guide to using Vue-Router to manipulate URL query parameters in Vue

I'm currently working on updating query parameters using Vue-router as I change input fields. My goal is to adjust the URL query parameters without navigating to a different page, but only modifying them on the current page. This is how I am approachi ...

An unexpected 'undefined' value is being added to a particular Web API request

I am encountering an issue in my Angular application where the word 'Undefined' is being appended to a specific WebAPI call, causing both registerUser and login requests to fail. Here are the problematic request URLs: Request URL: http://localho ...

Checkbox remains selected even after the list has been updated

I am currently dealing with an array of objects where each object has a property called "checked." When I click on a checkbox, it becomes checked. However, when I switch to another list, the checkmark remains even though it should not. Here's an examp ...