Can a button be validated if it is located outside of a form?

I'm currently in the process of developing a website to practice my coding skills and I have a query.

Can I implement button validation when the button is not within a form using HTML, CSS, and Bootstrap?

Check out the following code snippet:

<script>const submitButton=document.getElementById("submitButton");
const myForm=document.getElementById("myForm");
submitButton.addEventListener("click", function(event) {
  event.preventDefault(); // Prevent the button's default action
  // Check if the form is valid
  if (myForm.checkValidity()) {
    myForm.submit();
  }
  else {
    const formElements=myForm.elements;
    for (let i=0;
    i < formElements.length;
    i++) {
      if (!formElements[i].checkValidity()) {}
    }
  }
}

);
</script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="9efcf1f1eaedeaecffeedeaab0a8b0ac">[email protected]</a>/dist/css/bootstrap.min.css" integrity="sha384-xOolHFLEh07PJGoPkLv1IbcEPTNtaed2xpHsD9ESMhqIYd0nLMwNLD69Npy4HI+N" crossorigin="anonymous">

<div class="row">
  <div class="col-md-8 mb-4">
    <div class="card mb-4">
      <div class="card-header py-3">
        <h5 class="mb-0 text-font text-uppercase">Payment Details</h5>
      </div>
      <div class="card-body">

        <form id="myForm">


          <div class="row mb-4">
            <div class="col">
              <div class="form-outline">
                <label class="form-label" for="form11Example1">First name</label>
                <input type="text" id="form11Example1" class="form-control" style="text-transform: uppercase;" required/>

              </div>
            </div>
            <div class="col">
              <div class="form-outline">
                <label class="form-label" for="form11Example2">Last name</label>
                <input type="text" id="form11Example2" class="form-control" style="text-transform: uppercase;" required/>

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

          <div class="row mb-4">
            <div class="col-md-9">
              <div class="form-outline">
                <label class="form-label" for="form11Example1">Card Number</label>
                <input type="number" id="form11Example3" class="form-control" required/>

              </div>
            </div>
            <div class="col-md-3">
              <div class="form-outline">
                <label class="form-label" for="form11Example2">CCV</label>
                <input type="number" id="form11Example4" class="form-control" required />

              </div>
            </div>
          </div>
          <div class="form-outline mb-4">
            <label class="form-label" for="form11Example7">EXPIRATION DATE</label>
            <input type="date" id="form11Example5" class="form-control" required/>

          </div>
          <div class="back-to-shop"><a href="#">←<span class="text-muted">Back to shop</span></a></div>

          <div class="form-check d-flex justify-content-center mb-2">


          </div>
        </form>

        <div class="row">
          <div class="col-md-4">
            <img src="images/Boston Fern 1.webp" class="rounded-3" style="width: 100px;" alt="Blue Jeans Jacket" />
          </div>
          <div class="col-md-6 ms-3">
            <span class="mb-0 text-price">€23.00</span>
            <p class="mb-0 text-descriptions">Boston Fern </p>
            <p class="text-descriptions mt-0">Qty:<span class="text-descriptions fw-bold">1</span>
            </p>
          </div>
        </div>




        <div class="card-footer">
          <ul class="list-group list-group-flush">
            <div class="row">
              <div class="col" style="padding-left:0;">Item(s) total</div>
              <div class="col text-right">€ 47.00</div>
            </div>
            <div class="row">
              <p>Tax:</p>
              <p class="col text-right">€2.5</p>
            </div>
            <div class="row">
              <p>SHIPPING:</p>
              <p class="col text-right">€5.00 </p>
            </div>
            <li class="list-group-item d-flex justify-content-between align-items-center px-0 fw-bold text-uppercase">
              Total to pay
              <span>€54.5</span>
            </li>
          </ul>
        </div>
        <div class="text-center">
          <a id="button-payment" href="thanks-you.html">
            <button form="submitButton" id="button-pay" type="button" class="btn button-order col-md-10">PAY</button></a>


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

  </div>

I sought assistance from ChatGPT but it recommended adding an ID to the form and a form property to the button along with a JavaScript script, which hasn't yielded the desired result.

I'm simply curious about the feasibility of achieving this task.

Answer №1

It appears that there was a mistake made in the code:

const submitButton = document.getElementById("submitButton");

However, it seems that your button actually has the id: button-pay instead. By changing it to submitButton, you will be able to properly trigger the form validation as intended.

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

Error encountered: Unexpected token while trying to implement React + Node.js tutorial on a blog platform

I recently started following a tutorial on Site Point in an attempt to create my own React app. However, I hit a roadblock at these specific steps: mkdir public npm install npm run developement The first command failed for me because I already had a &a ...

Is there a way to capture the input from the text box and store it in the local storage?

I'm confused about why the data entered into the input box is not being saved to local storage. <body> <input id="name"> <button onclick="bob()"> save </button> </body> <script> const user = document.getElementByI ...

Tips for concealing items on a website within a WebView

Is it possible to hide the header element with the search bar and logo when loading this page on a Webview? I'm not familiar with JavaScript, so is there a way to achieve this? The section I am looking to conceal ...

Guidelines for aligning backend timer with a mobile application

I'm currently working on an app that randomly selects a user and provides them with a 15-second timer to respond. The user's app checks the database every 5 seconds to determine if they have been chosen. Once chosen, the mobile app initiates a 15 ...

In CSS, when text within a tab div lacks spaces, it triggers a horizontal scrolling effect

My special css style for the div: .message-body { background: #5181a2; padding: 8px 5px; text-align: justify; } I aim to display this particular text inside the div similar to how 'hello hello' appears on the line above. ...

Ways to fetch and present multiple columns in a single row from a database onto distinct HTML elements

Currently, I am working on a project that involves retrieving data from multiple columns of a single row in a MySQL database. The goal is to take the data from these different columns and display them in various places on an HTML webpage, using tags like & ...

Instructions on how to save HTML "innerHTML" along with attributes to a text document

I'm currently developing an HTML export feature from a DIV tag that includes various elements and attributes. HTML: <div id="master"><span class="classname">content goes here</span></div> <span class="download" onclick="ca ...

Sending a properly formatted string on Postman

My website allows users to answer coding problems. I am looking to store the questions and answers in a mongodb database. However, when testing the routes on my express application, I am encountering difficulties in sending formatted text in the request to ...

Sending a photo to a customer and launching it in a fresh browser window or tab with MVC 5

My question may be simple, but I find myself a bit puzzled. In my application, whenever a user clicks on an image's thumbnail, the ID of that thumbnail is sent to a controller action using AJAX: [HttpPost] public ActionResult GetHiResImage(string thu ...

Tips for effectively packaging the React 17 library alongside the latest JSX transformation feature as an ES Module

I am currently in the process of creating a basic library consisting of React components that I intend to publish as an ES Module package for NPM. With the utilization of React 17, I have incorporated the new JSX transform into my code. To generate the ES ...

A handy feature of HTML5 is the dataset attribute, which

Is there a way to restrict the height of the dataset dropdown list in HTML? When using <input list="datalist"> with numerous elements, some might not be visible. Is it possible to limit the size of the list and enable vertical scrolling to display al ...

Side menu and grid display using HTML and CSS

Looking to revamp the layout of my angularJS website, specifically one page. Currently, information is displayed in a table format but I would like to switch it up by adding a left sidebar featuring a list of names (tiles). When a user clicks on a name, th ...

Contentful integrated into a NuxtJs website

After successfully creating a blog using Nuxt JS and integrating Contentful into the project, I followed a helpful tutorial from here. This enabled me to retrieve all sections such as title, date, and content of the post efficiently. However, I am current ...

How to prevent selection of certain days in an Angular date input

I need help with my Angular component that includes an input date field. I am trying to figure out how to disable all past dates and also a specific range of future dates, such as those between 2023-10-15 and 2023-10-23. Is there a way to achieve this func ...

Utilize a function to save the data retrieved from each AJAX request

I am struggling to store accumulated data between ajax calls in an object. Even though I can retrieve the data from each call, I cannot seem to merge it into a single array. To address this issue, I have devised the dataAccumulator() function. The intenti ...

Complete Navigation Bar Expands Alongside Drop-down Menu

For my navbar, I am attempting to set a custom breakpoint at 1080px where it switches to a hamburger menu. However, when I click on a dropdown option, the entire navbar expands instead of just the dropdown area. @media (min-width: 1080px){ .navbar-expand- ...

What is the best way to eliminate the space between <div> elements?

I am looking to arrange <div> elements in a specific layout where one is at the top, three are in the middle in a row, and one is at the bottom without any extra space. It is necessary that there remains a space between the middle <div>s and th ...

Collect the text shown in an alert message created with JavaScript

I'm currently unsure if this is achievable or not. In one of my scenarios, I aim to extract text that appears in alert boxes on external websites by including my JavaScript file. Is there a method to obtain the text content shown in an alert message ...

A guide to implementing drag and drop functionality using JavaScript

I have developed a unique drag and drop application that features both a left and right panel. The issue I am facing is that when I drag the ball from the left panel to the right panel, it does get dragged successfully. However, the problem arises when the ...

JQuery causes Bootstrap carousel to malfunction after dynamically adding attribute to img tag

If you're thinking of sending me to this resource: Bootstrap Carousel not working after adding items dynamically with jQuery, know that the situation described there is different from mine. My issue involves fetching paths for 3 images from a JavaScr ...