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

Create a customized MUI select component with a label, all without the need for assigning an

One issue I am facing is with the Material UI React select component being used multiple times on a page. In the examples, all labeled selects use InputLabel with htmlFor that must match the id of the select. The challenge is that I cannot assign an id t ...

Guidelines for incorporating Context API in Material UI

Currently, I am encountering a TypeScript error while attempting to pass a property using the Context API within my components. Specifically, the error message reads: "Property 'value' does not exist on type 'String'" To provide conte ...

Is it possible to receive a unique value error even when providing the correct key value in a map?

I encountered an issue while using a map function with an array in my application. Even though I have provided a unique key, Google Chrome console is still showing an error related to the unique key. Error Each child in a list should have a unique "ke ...

Discover the steps for dynamically integrating ionRangeSliders into your project

Recently, I integrated ionRangeSlider to display values to users using sliders. To set up a slider, we need to define an input tag like this: <input type="text" id="range_26" /> Then, we have to use jQuery to reference the input tag's ID in or ...

Tips on incorporating a fresh item into a expansive tree view using a recurring function or action - specifically geared towards the MUI React JS Tree View component

I am looking to implement a function or action that allows for the dynamic addition of new items to a tree view in MUI. The goal is to be able to click on a tree item and have it add another item, repeating this process as needed. <TreeView ...

Error message: Unable to access $controller with AngularJS and Karma

As someone who is just starting with testing, I figured it was a good idea to begin testing this project. However, when I execute grunt karma:watch, I encounter an error related to the configuration files. My config file includes: module.exports = functi ...

Tips for dynamically populating a mat-table dataSource

While working with backend data streaming, I encountered an issue where trying to push an event to dataSource resulted in an error stating that dataSource is not defined. Can anyone provide guidance on how to dynamically add data to a materialize table? s ...

What is the best way to apply a CSS class to my anchor tag using JavaScript?

I have a good grasp of using JavaScript to insert an anchor element into my webpage. For instance, var userName_a = document.createElement('a'); However, I am interested in adding a style name to that same element as well. I attempted the follo ...

Bootstrap form toggle switch component for ReactJS

I'm having trouble figuring out why the default value for my react-bootstrap switch won't set to false (off). It seems like the only way it changes is when I trigger the onChange event handler. Am I overlooking something? Below is the section of ...

ReactJS and JavaScript offer a convenient solution for extracting the most recent date from an array of date fields during the selection process

I have a table in ReactJS that displays an array of items. Each item has the following fields: id, requested_date, and location Additionally, there is another field called "date" which is located outside of the array. This "date" should always display th ...

Toggle between a list view and grid view for viewing photos in a gallery with a

Hey there, I'm a newbie on this site and still getting the hang of jQuery and JavaScript. Though I do have a good grasp on HTML and CSS. Currently, I'm working on a photo gallery webpage as part of my school project using the Shadowbox plugin. Wh ...

Uploading a file to a .NET Framework API Controller using React

I am trying to figure out how to send files in the request body to an API controller in .NET framework using React. My goal is to achieve this without changing the request headers, so I want to send it as application/json. What I am looking for is somethi ...

Determine the number of days without including weekends and holidays using JavaScript

I am working on a code that calculates the total number of days excluding weekends and specified holidays. After researching on various platforms like stackoverflow and adobe forum, I have come up with the following code. If a public holiday falls on a w ...

incapable of utilizing the $q library and promises

I am trying to make use of the variable StatusASof within the inserthtml function in the following manner. App.controller("SS_Ctrl", function ($scope, $http, $location, $window, $sce, $q) { var ShiftDetails = []; function acquireMAStatusASof(Id) { ...

Is there a way to update an array within my class and access its updated output from outside the class?

let arr = [] class Test extends React.Component { handleConvertString = (event) => { let str = this.inputRef.value; let solutions = ['abb','klopp','lopp','hkhk','g','gh','a&apo ...

Is there a way to display the JavaScript widget exclusively on the homepage or main page

How can I limit the display of a Twitter widget on my blog page to only show on the main page and hide it when visitors navigate to sub-pages or individual blog entries? ...

Something strange happening with the HTML received after making a jQuery AJAX request

My PHP form handler script echoes out some HTML, which is called by my AJAX call. Below is the jQuery code for this AJAX call: $(function() { $('#file').bind("change", function() { var formData = new FormData(); //loop to add ...

It seems like KineticJS is removing elements from the canvas that I would prefer to keep

My website features an HTML5 canvas where I showcase a variety of images, text, and shapes using JavaScript functions. The text and shapes are created with the following JavaScript functions: function drawGameElements(){ /* Draw a line for the ' ...

Use JavaScript and AJAX to easily assign multiple variables with unique IDs to an array with just one click

This function is no longer supported Original query : I would greatly appreciate any assistance and guidance. I am attempting to create a function that moves selected products from the Cart to another table so I can reorder them according to customer de ...

Tips for extracting a specific attribute from an array of objects using both react and JavaScript while considering various conditions

I have a set of objects structured like this: const obj_arr = [ { id: '1', jobs: [ { completed: false, id: '11', run: { id: '6&apos ...