Change the behavior of a submit button to trigger a custom JavaScript function instead

I am faced with a challenge where I need to override the default functionality of a button in code that cannot be altered. Instead, I must ensure that when the button is clicked, a custom JavaScript method is called rather than submitting the form as it normally would.

To accomplish this task, I am required to use JavaScript injection within an AIR desktop application that utilizes the Twitter API.

Is there anyone who can provide assistance with this issue?

<body>
<form><fieldset class="buttons">
           <input class="submit button" id="cancel" name="cancel" type="submit" value="Cancel" />
</fieldset>
</form>
<body>

Answer №1

To prevent a form from submitting simply by overriding the click function may not be sufficient. Users can still submit the form using Ctrl+Enter.

You can achieve this functionality by following the steps outlined in this JSFiddle demo.

  1. First, locate the form assuming you have knowledge of the button id.

    function getForm(id) {
    
         var button = document.getElementById(id);
    
         while(button && 
              (button = button.parentNode) && 
              (button.nodeName !== 'FORM')){}
    
         return button;
    }
    
  2. Next, add a 'submit' event listener to the form.

    var form = getForm('cancel'),
        handler = function(ev){
        ev = ev || window.event;
        if(ev.preventDefault) { //for modern browsers
            ev.preventDefault();    
        }
        else { //for old Internet Explorer versions
            ev.returnValue = false;    
        }
        alert('Custom logic goes here!'); 
    };
    if(form) {
        if(form.addEventListener) {
           form.addEventListener('submit', handler, false)   
        }
        else if(form.attachEvent) {
           form.attachEvent('onsubmit', handler);   
        }    
    }
    

Answer №2

Swap it using JavaScript with a new button that triggers your custom function

document.getElementById('cancel').parentNode.innerHTML = '<input type="button" onClick="onClickFunc()" value="swap">';
window.onClickFunc = function() { alert('Button clicked!'); return false; }

http://jsfiddle.net/p4dwq/

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

Exploring Ngrx: Leveraging a single selector to choose multiple property modifications

I need some help with my reactive Form Angular application that uses the NGRX store. Instead of subscribing to the entire state, I want to subscribe to changes in specific fields like "name" and "city." I have been attempting to use the selector selectFor ...

Updating contact list to a database table structure

Currently, my code displays the data in address books, but I would like it to be shown in a table instead. I attempted to use document.write to create the table, but I'm unsure how to populate the table with the data rather than the address book forma ...

When using Angular $http.post, encountering issues with the 'Access-Control-Allow-Origin' header

I have developed two applications using nodejs and angularjs. The nodejs app contains the following code: require('http').createServer(function(req, res) { req.setEncoding('utf8'); var body = ''; var result = '&a ...

Transferring PHP array to JavaScript with the help of AJAX

I've been working on integrating Google Maps and Instagram in a project of mine. My main challenge is figuring out how to pass the coordinates of Instagram photos from my PHP file to my JavaScript file using AJAX. I'm quite lost when it comes to ...

Retrieve and utilize the dynamically produced values from the application's app.js in a script that is accessed using

In my Express.js Node web app, I generate a string in app.js during initialization: // app.js var mongourl = /* generated based on process.env.VCAP_SERVICES constant */; There is a script that I import into app.js using require(): // app.js var db = req ...

The code is functioning properly, however it is returning the following error: Anticipated either

Can you explain why this code is resulting in an unused expression error? <input style={{margin:'25px 50px 0',textAlign:'center'}} type='text' placeholder='add ToDo' onKeyPress={e =>{(e.key ==='En ...

Code in Javascript that performs a check for pre-order traversal

I’m interested in writing a preorder traversal code in Java for JavaScript. I’ve been practicing this question on geeksforgeeks: Check if a given array can represent Preorder Traversal of Binary Search Tree This is the algorithm they provided: 1) Cr ...

Creating a two-dimensional canvas within a div element using the console

I have some code that currently generates an image in the console when I hit F12. However, I would like to display this image inside a more user-friendly area such as a div on the webpage. I attempted to create a <div class = "mylog"> to place the i ...

Can you guide me on utilizing filter in an Apps Script array to retrieve solely the row containing a particular user ID within the cell?

I am using an Apps Script that retrieves data from four different columns in a spreadsheet. However, it currently fetches all the rows instead of just the row that matches the randomly generated 8-digit user ID. function doGet(req) { var doc = Spreadshe ...

The functionality of document.elementFromPoint(x, y) seems to be faulty in accurately identifying child elements

I've been trying to retrieve the element over which a "drop" event occurs, but I keep getting unexpected results. It consistently returns parent elements instead of the actual child element where the dragged element is dropped on. For a full code exa ...

Why does the implementation of my interface differ from what is specified in the TypeScript documentation?

Currently delving into the world of TypeScript documentation https://www.typescriptlang.org/docs/handbook/2/classes.html Specifically focusing on the section implements Clauses, an interesting revelation surfaces: A Word of Caution It’s worth noting t ...

Subdomain for an Ajax request

Can we use ajax requests to extract data from and fetch information from pages like ? It appears that JavaScript still does not permit subdomain requests. ...

The value on the input of a custom Vue component does not update as expected when using v

I'm currently working on a custom component called customCombobox. It functions similarly to a regular v-combobox, but with an added feature - after the user presses the tab key, it automatically selects the first option available. Everything in my i ...

Saving Selected Radio button values into Jquery Array

In my HTML table, there are multiple rows with radio buttons representing the sexes in the 0th position of <td>. I am trying to store the values of sex (either 1 or 0) in an array. Below is a snippet for a table with 3 rows. HTML Code: <table> ...

Error encountered: The JSON format provided for Spotify Web-API & Transfer User's Playback is invalid

Utilizing the spotify-web-api-js has been a smooth experience for me when interacting with Spotify Web API. However, whenever I attempt to use the transferMyPlayback() method to switch devices, I consistently run into an error response indicating a malfor ...

Express encountered an issue when trying to upload a file through AngularJS

I am currently facing an issue with uploading a file to express and subsequently to mongoDB. Despite my efforts, when I attempt to upload the file to express, it appears that no data is being passed through the response. I am utilizing ng-file-upload.min. ...

transforming a div to behave similarly to an iframe

I am trying to load content from my page into a div element using the following function: function loadmypage(DIV, pageURL) { var xmlhttp; if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp=new XMLHttpRequest(); } e ...

I need to confirm the validity of minDate and maxDate in a ReactJS component, ensuring that maxDate is always at least 5 years after min

start from today and select a date end 5 years from the starting date I haven't attempted anything yet. Seeking help for a solution. ...

Error: Missing semicolon at line 1005 in Vue computed function. Vetur is indicating this issue

As a beginner in vue3, I am venturing into building some side projects. However, I keep encountering an error message stating ';' expected.Vetur(1005) when attempting to utilize the computed function. Strangely enough, sometimes the same syntax w ...

I've been stuck on this for the past hour, trying to figure out why /js/bootstrap.min.js can't be located

I'm having an issue with the code in base.html while trying to create a bootstrap starter template. I copied it from bootstrap but when I run it, I get an error related to /js/bootstrap.min.js. Can someone help me figure out what's wrong? Thank y ...