Complete the form even if the field is mandatory by leveraging the Bootstrap Checkout demonstration

I devised a straightforward form for entering text. The input of this text is mandatory.

However, when I click on the submit button, the form gets submitted even if the required text field is empty.

I took inspiration from this particular Bootstrap template.

// Here's an example starter JavaScript code that disables form submissions with invalid fields
(function() {
  // 'use strict'

  window.addEventListener('load', function() {
    // Get all the forms we want to style with custom Bootstrap validation
    var forms = document.getElementsByClassName('needs-validation')

    // Loop through them and stop submission
    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)
}())

$("#suche").submit(function(event) {
  alert("Handler for .submit() called.");
  event.preventDefault();
});
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" rel="stylesheet" />

<div class="container">
  <div class="row">
    <div id="karte1" class="col-md-7 order-md-1">
      <form class="needs-validation" id="suche" novalidate>
        <div class="mb-3">
          <div class="input-group">
            <input type="text" class="form-control" id="username2" required>
            <div class="input-group-append">
              <button type="submit" class="btn btn-outline-secondary">
                  submit
                </button>
            </div>
            <div class="invalid-feedback" style="width: 100%;">
              Valid text is required.
            </div>
          </div>
        </div>
      </form>
    </div>
    <!-- Karte1 -->
  </div>
  <!-- row -->
</div>
<!-- container -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js"></script>

Appreciate your assistance!

Answer №1

Perhaps you could consider utilizing the html required attribute?

I intended to leave a comment, but unfortunately I lack the necessary reputation.

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

Adding DIV elements within a Bootstrap Carousel

I've successfully placed containers inside my Bootstrap Carousel slides that overlay the image with text and a link. It looks great initially, but I'm facing an issue where after switching to the next slide, I can't return to the one with th ...

Ways to align div elements

I am currently in the process of developing my own custom animation player. Utilizing Three.js for object rendering has been successful so far. However, the challenge lies in incorporating control options at the bottom of the player interface (such as play ...

Save Chrome's console log programmatically

Can anyone provide insights on how to use javascript or nodejs to automatically extract the contents of Chrome's console for saving it into a file or database? ...

Bootstrap - creating seamless navigation between accordion sections on a single webpage

I am currently attempting to create internal links within an accordion menu on the same page. Here is the code I have been working with: <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> & ...

List all directories before accessing them using fs.readdirSync

Looking to fetch the contents of a directory from my system. Here is the structure https://i.sstatic.net/Qhwkg.png This code helps me read the directory: const directoryLevelInfo = fs.readdirSync('data', 'utf8') ...

Update all unique symbols excluding the initial instance of the addition symbol

I need a solution to replace all non-numeric characters in a string, excluding any leading "+" signs. For example: 1234++!@#$%^&*()_+=-;',.><:" becomes 1234 +1234 becomes +1234 ++++1234 becomes +1234 +1234++!@#$%^&*()_+=-;',.&g ...

The compatibility of Datatables responsive feature with ajax calls appears to be limited

I recently started using the datatables plugin and have encountered an issue with responsive tables. While I successfully implemented a responsive table and an AJAX call on a previous page, I am facing difficulties with it on a new page for unknown reasons ...

AngularJS factory architecture for multiple functions

It's not the exact data I'm using in my project, but I'm simplifying it for demonstration purposes. In my AngularJS app, I have a factory like this: myApp.factory('inputinfo', function () { var self = { test: function (in) { ...

Exploring recommendations using AngularJS

I am currently working on replicating the search suggestion feature found at: where certain words are displayed as you type in the search box. Here is my HTML setup: <form ng-controller="SearchCtrl"> <input name="q" ng-model="query" ng-keyp ...

What is the best way to pinpoint the origin of the element.style being injected by JavaScript?

I've been tasked with updating a client's WordPress website, but I'm still getting acquainted with the overall structure of the site. When looking at the blog page (), I noticed that posts are displayed within a wrapper labeled #blogleft, a ...

After executing grunt serve, Bower issues a warning for jquery stating "not injected"

Recently, I had to clone a project and rebuild bower packages. It seems that jQuery has been updated, causing a warning to appear: Warning: Please check the "app/bower_components/jquery" folder for the necessary file and manually include it in your ...

I'm curious about something as a beginner. Can you explain what **.config.js and **.vue.js files are? How do they differ from regular .js files

I have a simple question that I haven't been able to find the answer to through searching. I've come across files like vue.config.js generated by vue-cli, as well as files like Content.vue.js. At first, I assumed that after the period was the fi ...

What is the process for producing multiple objects in JSON format and then accessing them from within <g:javascript> in Grails?

My goal is to add two select boxes within the results div using Ajax. I have a function named ajaxFun that retrieves values for the select boxes. However, I am struggling with rendering multiple objects as JSON and then retrieving them in my JavaScript fun ...

Having difficulties in dynamically swapping audio sources using JavaScript?

It seems like I'm overlooking something simple here. The issue I'm facing involves creating a series of buttons with different audio sources as titles. When a user clicks on a button, the corresponding source should update in the audio player. T ...

Is there a method for decreasing the expected conv2d_Conv2D1_input from 4 dimensions to 3?

Issue: An error message states that conv2d_Conv2D1_input is supposed to have 4 dimensions, but the array provided has a shape of [475,475,3] However: The inputShape is configured as [475,475,3] Upon inspection, tensors exhibit the shape [475,475,3] Err ...

Phantom.js: Exploring the Power of setTimeout

Below is a snippet of code that intends for Phantom.js to load a page, click on a button, and then wait for 5 seconds before returning the HTML code of the page. Issue: Utilizing setTimeout() to introduce a delay of 5 seconds leads to the page.evaluate fu ...

Error: The function _this[("render" + data.type)] is not defined as a valid function

https://i.stack.imgur.com/Y5Dz5.jpg I encountered an error in the console that I can't seem to figure out. Despite following the Syncfusion library's documentation, the error persists. Here is the code snippet that I implemented: import React f ...

Are you wondering why there isn't a straightforward solution for swapping page content using JavaScript?

Is there truly no straightforward solution to the issue at hand - specifically, swapping HTML content on web pages? In this scenario, using jquery's load() isn't viable because I need to load a file locally for Node-webkit, and due to Cross orig ...

Sharing data with external domains and retrieving HTML output using JavaScript

When a browser sends a POST request and expects an HTML page result from JavaScript, problems arise if there is no Access-Control-Allow-Origin in the server response. Unfortunately, changing anything on the server side is not an option. If a human clicks ...

Analyzing and adding Angular JSON information

I'm struggling to understand why the compare function and insert function in my code aren't functioning correctly. I suspect that one reason for this could be that the function is not being called by the button. How can I confirm this? It seems l ...