Validating and submitting forms using Bootstrap 4

I recently integrated a Bootstrap 4 form with validation using the provided "starter" JavaScript code available on their official website: https://getbootstrap.com/docs/4.4/components/forms/#validation.

This form is located within a sidebar of a Google Docs add-on. Upon form submission, I do not intend to redirect to another URL. Instead, I aim to collect the form data and handle it using Google Apps Script.

Despite the validation of form fields working as expected with the starter JavaScript, after submitting the form, a new browser tab opens, which is not the desired behavior.

I made a modification to the starter code below where I call my custom function from within the 'else' block. Presently, my function, submitFeedback(), only triggers an alert confirmation, yet upon invoking submitFeedback(), a new tab pops up in the browser.

How can I prevent this new browser tab from opening each time the form is submitted?

<form class="needs-validation" novalidate>
    <div class="form-group">
        <label for="frmFirstName">First name</label>
        <input type="text" class="form-control" id="frmFirstName" placeholder="First name" required>
        <div class="invalid-feedback">
            Please enter your first name.
        </div>
    </div>
    ... (Remaining form fields)
    <button class="btn btn-primary btn-sm" type="submit">Submit form</button>
</form>


...

<script>
// Example starter JavaScript for disabling form submissions if there are invalid fields
(function() {
  'use strict';
  window.addEventListener('load', function() {
    var forms = document.getElementsByClassName('needs-validation');
    var validation = Array.prototype.filter.call(forms, function(form) {
      form.addEventListener('submit', function(event) {
        if (form.checkValidity() === false) {
          event.preventDefault();
          event.stopPropagation();
        } else {
        submitFeedback();
        }
        form.classList.add('was-validated');
      }, false);
    });
  }, false);
})();

function submitFeedback(){
    alert ('inside feedback function');
}
</script>

Answer №1

When testing in the latest version of Firefox and Chrome, I noticed that the code is not opening a new tab as expected. It's worth checking whether you are using a local web server and if there are any specific configurations set there. Additionally, if you are using a different browser, it's possible that this behavior is browser-specific. To troubleshoot, try clearing the browser cache and utilizing developer tools to get a better understanding of what's happening behind the scenes.

Answer №2

The main issue causing the problem was the base target in the head section of the HTML file. Once it was removed, everything functioned as expected. This specific tag is automatically inserted when a new HTML file is created using the Google Apps Script editor.

<head>
    <base target="_top">
 </head>

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

Enabling the execution of returned scripts using JQuery AJAX

I have a hyperlink that I need to send a DELETE request using JQuery through AJAX. if(confirm("Do you wish to proceed?")) { $.ajax({ url: $(this).attr("href"), type: 'DELETE', success: function(result) { // Perform act ...

Ways to position the navigation menu alongside a search bar and a dropdown tab?

My navigation bar includes a search form, multiple links, and a dropdown link leading to additional links. Unfortunately, I'm struggling to align everything on the same line within the navbar. This is the current output: View My HTML Page Below is ...

Updating the background of a button with Vue JS by utilizing an object upon clicking

If you have three buttons and want to change the background color when clicked, for example, clicking on the red button should turn the background color red. However, there is an important detail here: if you click on one button and then another, the old c ...

Trigger ng-click after ng-model updates

Is there a way to create an ng-click function that will only execute after the value of the ng-model in a scope variable changes? In my scenario, I have a list of analysis objects within a list called analyses, each with an include boolean attribute used f ...

Asynchronous NestJs HTTP service request

Is there a way to implement Async/Await on the HttpService in NestJs? The code snippet below does not seem to be functioning as expected: async create(data) { return await this.httpService.post(url, data); } ...

Get rid of an element in a Javascript array and show the updated array contents

In the following code block, I have implemented a simple functionality that allows me to display a list of items from an array, remove a selected item from the list, and then display the updated list without the deleted item. var carBrands = ["Toyota", "H ...

My program is throwing an error due to invalid JSON format

Snippet of code: var data = $.parseJSON(data); Error message: Encountered Invalid JSON: {times: [{'9:30am','10:00am','10:30am','11:00am','11:30am','12:00pm','12:30pm','1:00pm&apo ...

The error message states that the provided callback is not a valid function -

I seem to be encountering an issue with the code snippet below, which is part of a wrapper for the Pipl api: The main function here performs a get request and then retrieves information from the API Any assistance in resolving this error would be greatly ...

Having trouble sending JSON data to the server using a POST request

I am encountering an issue while attempting to send JSON data to the server using the fetch API and PHP as the server-side language. The PHP code on the server side is quite simple: <?php header("Access-Control-Allow-Origin: *"); header("Access ...

I'm trying to find the location of the server.js file in Node

Currently, I am diving into a book that delves into the integration of nodejs and backbonejs. It covers the foundational aspects that serve as the building blocks for understanding. (...) To kick things off, execute the command 'npm install express& ...

The alignment of elements in the div seems to be slightly skewed

Currently, I am in the process of creating a website with the temporary name yeet.io. I am facing an issue where I am attempting to center both an input and h1 element inside a div vertically and horizontally, but they keep appearing misaligned for some r ...

The Backbone.js template does not automatically inherit attributes from the model

Hey there, I'm currently working on setting up a simple SPA using Backbone for testing purposes. However, when I try to render my view, the Underscore template doesn't seem to be picking up any attributes from my model. I've been trying to t ...

Obtaining the most recently inserted ID in Node.js can be achieved by using

Currently in my Nodejs project, I am using the expressjs framework. I am facing an issue where I am trying to retrieve the "last inserted id", but it is showing as "undefined" in the console. How can I successfully get the last inserted id? Below is the ...

Utilize Express efficiently by requiring modules only once for multiple routes within the application

Here is an overview of my project directory structure: MyProject -app.js -routes -routeone -routetwo In the app.js file, I have the following setup: var express = require('express'); var app = express(); var routeone = ...

Validate if the JSON data array contains any elements

I'm currently working with an ajax code and I need to determine whether the JSON data contains an array or not. However, despite my attempts, I am still receiving incorrect output. $.ajax({ url: url, type: 'POST', da ...

What is the best way to compare two arrays that have elements of different data types?

Can someone help me compare two arrays in TypeScript to see if they are identical? I'm having trouble with the current code. Here's what I have: let props:(string|boolean)[]=['abc','def',true,false,'xyz'] let propsCo ...

Customize the shadow array values in Material UI themes by utilizing the createMuiTheme function to override default

Currently, I have a customized theme for my toolkit where I am utilizing createMuiTheme to override various properties like palette, fonts, etc. One particular challenge I am facing is in minimizing the shadow array within the theme object which contains 2 ...

Update settings when starting with chromedriver

I am currently using webdriver (), standalone selenium, and mocha for writing my test cases. These test cases are specifically designed for Chrome, so I rely on chromedriver for execution. However, when launching the browser, I need to ensure that the "to ...

Implementing styling upon app mounting in Vue.js - a step-by-step guide

Hey, I'm working with a template code that looks like this: Here's my script code: data () { return { loadPage: true } }, mounted () { this.loadPage = true }, And here is my styling code: #app{ width: 100%; opacit ...

Update the Ngrx reducer when the component is present on the page

One dilemma I am facing involves managing two components within a page - an update user form and a history of events. Each component has its own reducer (user and events). My goal is to update the list of events in the store through an API call once the us ...