What is preventing the JavaScript redirect from functioning in this scenario?

Within my HTML file, there exists a form containing a submit button as shown below:

<button id="submit">Submit</button>

In my JavaScript file, I wrote the following code:

window.onload = function() {
    document.getElementById("submit").onclick = form_action;
}

function form_action() {
    window.location.href = "www.google.com";
}

However, upon clicking the submit button, the redirect to another webpage does not occur. The only way I was able to make it work was by inserting alert(location.href) after

window.location.href="www.google.com";
. It seems like this forces the window to update?

How can I resolve this issue without modifying my HTML file or utilizing JQuery? Why is this problem happening in the first place? Any insights and solutions using solely JavaScript would be greatly appreciated.

I am looking for a pure JavaScript solution and prefer not to alter my HTML file or resort to Jquery.

Answer №1

By default, a <button> element has a type of "submit". This means that when the button is clicked, it will submit the form it belongs to. However, if you specify type="button", the <button> will no longer have this default behavior. Instead, it will only execute the JavaScript code that you provide.

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

Populating an array in JavaScript with specific values from another array to meet a certain criteria

Looking to implement a function called populateAnimalArray, which takes an array as input and populates it with additional elements based on another argument specifying the required number. const animals = ['lion', 'tiger', 'cheet ...

Issue with AngularJS Directive: Encountering an error stating "Unexpected token"

Currently working with version 1.20 rc2 and attempting to incorporate a directive: var directives = angular.module('directives', ['controllers']); directives.directive("drink", function() { return { template: '<div>{{f ...

Ways to resolve an unhandled promise in audio issues

A scenario where a piece of JavaScript is used to manage multiple audio elements is demonstrated below. var audio = []; audio["blue"] = new Audio("piano-blue.wav.mp3"); audio["red"] = new Audio("piano-red.wav.mp3"); ...

prevent scrolling to a specific div

Hey, I'm facing a slight issue and need to prevent scrolling to the div after clicking on a link that targets the left div. <div class="kafelki"> <div class="kafelki-img"> <div class="target"> <div id="m1">dasdasdasd m1</di ...

Performing web scraping on a page rendered with Javascript in Python 3.5

I'm currently working on a project that involves extracting a dynamically rendered table using Python 3 and a webdriver. Below is the code I have implemented: from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait fro ...

What is the best way to place a semi-transparent black overlay on an image?

<html> <head> <style> #contain_main {background-color:black; width:100%; height:auto;} #main {width:100%; height:700px; background-image:url("https://www.sappun.co.kr/shopimages ...

Difficulty transferring information between two components by using services

I am trying to pass the values of an array from the Search component to the History component in order to display the search history. My current code structure looks like this: search-page.component.ts export class SearchPageComponent implements OnInit ...

I have a desire to use Javascript to control CSS styles

Within the CSS code below, I am seeking to vary the size of a square randomly. This can be achieved using the Math.random() property in Javascript, but I am uncertain how to apply it to define the size in CSS. #square { width: 100px; height: ...

Justifying content is failing to perform its duty, while aligning items is successfully fulfilling its role

Can someone explain why the align-items property in this code is centering child elements on the x-axis instead of the y-axis? Also, the justify-content: center doesn't seem to have any effect. Even when I remove justify-content, the items are still a ...

Unintroduced jQuery Keyup

I am currently working on a project where I am trying to incorporate an autocomplete feature into an input form. My approach involves using jQuery to trigger an AJAX call to a servlet and adding a listener on the input field for keyup events. However, it s ...

Accessing a nested JSON array with duplicated attribute names

Is it feasible to access the values in the 'Roofing Insulation' array using JavaScript, especially when dealing with duplicate attribute names? I've attempted various syntaxes like productListing['Roofing Insulation']['Roofin ...

What could be causing the error message 'Uncaught SyntaxError: Identifier 'randFilmIndex' has already been declared'?

function getRandomInt(min, max) { min = Math.ceil(min); max = Math.floor(max); return Math.floor(Math.random() * (max - min) + min); } function arrayRemove(arr, value) { return arr.filter(function(ele){ return ele != valu ...

"Step-by-step guide to updating user information in MongoDB with the help of node.js

I have been working on a basic express app with MongoDB integration, allowing users to register, log in, and log out successfully. However, I am facing an issue when attempting to implement the functionality to edit user data. The code runs without any err ...

Mass delete MongoDB documents using NodeJS

I'm dealing with a collection containing some messy data that I need to bulk delete based on a certain criteria. While it's a simple task in the mongo shell using db.collection.remove() with the justOne option, I'm wondering if there's ...

What is the best way to integrate my custom JavaScript code into my WordPress theme, specifically Understrap?

I am looking to enhance my website with a sticky navbar positioned directly under the header, and I want it to stick to the top of the page as users scroll down. Additionally, I want the header to disappear smoothly as the user scrolls towards the navbar. ...

Guide on creating a rectangle in HTML without using the canvas element

The concept is clearer in this image In the photo provided, I utilized canvas for drawing; however, I am interested in exploring a different approach that would allow me to create draggable rectangles with unique IDs. For instance, if I were to use div in ...

Unable to perform queries from a separate file as connection.query function is not recognized

Currently diving into node.js and databases. Attempting a mysql query, but encountering the error TypeError: connection.query is not a function. Utilizing Node MySQL 2 (https://www.npmjs.com/package/mysql2) package; The connection and queries in app.js f ...

Transmitting information via Ajax, jquery, Node.js, and Express

Seeking assistance as I struggle to comprehend the process while trying to implement it based on various online resources. My carousel directs users right after signing up, and I aim to gather information about their profile through simple input questions. ...

JQuery auto complete using ajax response to populate data set is not displaying any results

I've encountered a problem with jQuery autocomplete using AJAX data as the source. The data is being returned correctly without any errors, yet the results are not displaying as expected. I've searched through various Stack Overflow questions re ...

The TypeError: Property 'subscribe' is not readable because it is undefined

Currently, I am developing an Ionic application and encountered the following method that invokes an observable: fetchCountryById(id: number): Promise<Country> { return new Promise((resolve, reject) => { this.obtainCountries().subscri ...