Enhancing the submit button features in a validation form with Bootstrap 4

Despite multiple searches on Google, I haven't been able to find a solution to my problem. I'm using a validation form from bootstrap 4 and all I want to do is link a button to a different page. Using the anchor tag like this:

<a href="www.mysite.com" class="btn btn-primary btn-lg active" role="button" aria-pressed="true">Submit</a>

works, but it bypasses the validation process.

Currently, I have this button within a form:

<button  class="btn btn-primary" type="submit" >Submit form</button>

</form>

And here is the JavaScript that goes with it:

<script>
// Example starter JavaScript for disabling form submissions if there are invalid fields
(function() {
  'use strict';
  window.addEventListener('load', function() {
    // Fetch all the forms we want to apply custom Bootstrap validation styles to
    var forms = document.getElementsByClassName('needs-validation');
    // Loop over them and prevent submission
    var validation = Array.prototype.filter.call(forms, function(form) {
      form.addEventListener('submit', function(event) {
        if (form.checkValidity() === false) {
          event.preventDefault();
          event.stopPropagation();
        }
        form.classList.add('was-validated');
      }, false);
    });
  }, false);
})();
</script>

I would appreciate any help in figuring out what needs to be added to the javascript file in order to make the button functional. Thank you!

Answer №1

Here is a simplified version with heavily commented code for better understanding.

// The script waits for the page to load before executing
window.onload = () => {
  // Selecting the form to validate
  let form = document.querySelector('form');

  // Listening for the submit event
  form.onsubmit = (event) => {
    // Preventing the form from submitting and refreshing the page
    event.preventDefault();
    // Debugging log statement (optional)
    console.log('Form submitted')
    // Checking for form validation
    if (form.checkValidity() === false) {
      // Adding bootstrap class for styling if form is invalid
      form.classList.add('was-validated');
      // Debugging log statement (optional)
      console.log('Form not valid')
    } else {
      // Redirect to target page if form is valid
      location.href = "www.example.com"
    }
  }
};
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css">
<form class="needs-validation" novalidate>
  <div class="form-row">
    <div class="col-3">
      <label for="validationCustom01">First name</label>
      <input type="text" class="form-control" id="validationCustom01" placeholder="First name" value="Mark" required>
      <div class="valid-feedback">
        Looks good!
      </div>
    </div>
    <div class="col-3">
      <label for="validationCustom02">Last name</label>
      <input type="text" class="form-control" id="validationCustom02" placeholder="Last name" value="" required>
      <div class="valid-feedback">
        Looks good!
      </div>
    </div>
    <div class="col-3">
      ...
      // Additional HTML code generated by Bootstrap
      ...
    </div>
  </div>
  <button class="btn btn-primary" type="submit">Submit form</button>
</form>

If you are new to coding, it's recommended to start with vanilla JavaScript and CSS without relying on libraries. Build projects from scratch and research each line of code thoroughly. Once you have a solid foundation, then you can explore using libraries and frameworks.

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

One Versatile Ajax Function for Accessing Various PHP Pages

On my index.html, there are buttons displayed below: <button value="about_us.php" onClick="fNt(value)">About Us</button> <button value="faq.php" onClick="fNt(value)">FAQ</button> <button value="contact_us.php" onClick="fNt(val ...

Sharing the logger object in NodeJS projects: What's the best approach?

After setting up a logger object in the file utils/logger.js using the winston package, I am wondering how to propagate this logger object to all project files (approximately 20 in total). Do I need to include const logger = require('../utils/logger&a ...

fetch a particular value using jQuery and display it

Seeking assistance here! I am in the process of consuming a Web Api service from an MVC ASP.NET App using jQuery's function $.ajax. The goal is to retrieve a specific record from the database. While I can successfully connect to the service and fetch ...

Implementing jQuery form validation including checking for the strength of the password

My understanding of jQuery was quite basic until I began working on jQuery form validation with password strength check. I successfully completed the password strength check portion, but now I am unsure of how to enable the submit button once the condition ...

Ensure all divs have equal heights based on the tallest one, without compromising the responsiveness of the layout

I'm facing a challenge with my webpage that consists of multiple divs placed next to each other, each containing an image and text. Due to varying content lengths, the height of these divs ends up being different. Is there a way, without manually sett ...

Discover the method for running Linux commands through a client/server architecture

My goal is to create a web application where clients can log in and run Linux commands. What is the best way to achieve this? Should I use HTML/JavaScript with a PHP backend on Apache, or should I consider using Node.js? Do I need a Linux machine running ...

Implementing a Vue.js v-bind:style attribute onto a dynamically generated element post-page initialization

Let me start by explaining my current issue and dilemma: I have been tasked with converting an existing JS project into a Vue.js framework. While I could easily solve a particular problem using jQuery, it seems to be posing quite a challenge when it comes ...

Warning in Chrome about percentage-based rows for tracks and gutters

My CSS contains a line that reads: grid-template-rows: 20% 80%; Interestingly, when I launch the application in Chrome, a deprecation warning pops up in the console. However, this warning does not appear when using Safari or Firefox. The warning message ...

Designing a dropdown menu within displaytag

I am currently utilizing displaytag to present tabular data, but I aspire to design a user interface akin to "kayak.com" where clicking on a row reveals additional details without refreshing the page. Here is an example scenario before clicking the Detail ...

What is the correct way to properly embed a form within a div using HTML and CSS?

I am struggling to get things aligned correctly. Currently, I have two background image divs for content and a footer. My goal is to anchor the form to the top of div_11, but it keeps ending up at the bottom and causing parts of it to be hidden. <div i ...

Using an Ajax Post Call to send FormData leads to a Get request instead

Having trouble with sending a simple form via POST method. I load the form content using AJAX: $(function() { var arg = { "operation": "upload", "step": "0" ...

Adding an hour to a time value with preg_replace: A step-by-step guide

On my page, I display times like this: 10:00am. Now, I'm looking to add one hour to each of these displayed times. I've managed to create a regular expression that helps locate the times in the format required, but I'm stuck on what steps to ...

Automatically scrolling down with Vue3 and Ionic: A seamless scrolling experience

In the process of developing a VueJS App with Ionic, there is a Chat feature involved. It is crucial for users to view the latest message first and not the oldest one, so it is necessary for the app to open with the container scrolled to the bottom. Additi ...

Persistent header feature in AdminLTE 3: Easily navigate while scrolling

I am looking to make the elements in the red box on the left side of the page fixed so that as users scroll, they remain at the top of the page. I have attempted to use both the fixed and sticky properties, but neither seem to be working for me. Here is a ...

Unable to style bootstrap navbar with CSS

Can anyone help me troubleshoot an issue with custom styles not displaying correctly on my home page but showing on another page? index.php <?php include 'include/css.php';?> <?php $page = 'home';include 'include/navbar. ...

What could be causing my CSS background to repeat multiple times along the page?

I am experiencing an issue with the code below where it is creating the desired background but duplicating it twice down the page. Can someone explain why this is happening and how can it be prevented? The testing environment I am using is Google Chrome. ...

Automatic popup updates when submitting a form in a Chrome extension

Looking to develop a chrome extension popup window that, when clicked, will present a form for users to input their name and college. The goal is to save this data in chrome storage and then replace the popup with a new window displaying a greeting message ...

Cannot render <Image> inside <Section> component

As a beginner in React, I am attempting to create an app following a tutorial. In my component, I utilized the figure tag but it's not showing up when inspecting element in Chrome. Here are the code snippets: The tutorial includes a div tag as a chil ...

Because of the CSS tree structure, it is not possible to add or remove classes. This restriction applies to all actions done in jQuery, including click

I want to create a hover effect where the CSS changes when hovering over an item, then reverts back to normal when no longer hovered. Additionally, I would like the CSS to change when the item is selected, and return to normal when another item in the same ...

Having issues with jQuery Overlay functionality on Internet Explorer 8

Sorry if this question has already been addressed elsewhere, but I wasn't able to locate any information on it. I am currently using jQueryTools Overlay which is functioning properly in Chrome. However, I am encountering an issue in IE-8 where my ove ...