Merging onsubmit attribute with jQuery submit event listener

My website has a form that is automatically generated by older server-side code. Unfortunately, I am unable to make any modifications to this legacy code for various reasons. The form itself is written in straightforward HTML:

<form action="#" id="theForm" onsubmit="return check_theForm(); method="post">
  <!-- fields go here -->
</form>

Upon submission of the form, the onsubmit parameter triggers and calls the check_theForm() function, which uses pure JavaScript (no jQuery involved) to ensure that all required fields have been completed.

Now, my goal is to integrate reCAPTCHA V3 into this form. To achieve this, I've added the following script:

$('#theForm').submit(function(event) {
  event.preventDefault();
  grecaptcha.ready(function() {
    grecaptcha.execute('xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
      {action: 'contactForm'}).then(function(token) {
        $('#theForm').prepend('<input type="hidden" name="token" value="' + token + '">');
        $('#theForm').prepend('<input type="hidden" name="action" value="contactForm">');
        $('#theForm').unbind('submit').submit();
      });;
  });
});

The problem arises because the onsubmit parameter of the form fires before the

$('#theForm').submit(function(event)
handler, causing check_theForm() to be executed twice. As a result, if there are any errors in the form, they will appear duplicated.

I'm looking for a solution to prevent this duplication issue without modifying the form's HTML or altering the check_theForm() function. It is crucial to note that these components are generated by legacy server-side code, which I don't have authorization to edit.

Answer №1

When you use the onsubmit="x()" attribute, you have the option to remove the HTML onsubmit handler by executing the following code:

$("#id").attr("onsubmit", null);

This will give you complete control over your form without relying on the default event handler.

Alternatively, if you specifically want to remove the onsubmit attribute for a form with an ID of "theForm," you can use the following code:

$("#theForm").removeAttr("onsubmit");

$('#theForm').submit(function(event) {
  event.preventDefault();
  grecaptcha.ready(function() {
    grecaptcha.execute('xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
      {action: 'contactForm'}).then(function(token) {
        $('#theForm').prepend('<input type="hidden" name="token" value="' + token + '">');
        $('#theForm').prepend('<input type="hidden" name="action" value="contactForm">');
        if (check_theForm())
            $('#theForm').unbind('submit').submit();
      });;
  });
});

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

Contrasting the utilization of jQuery versus angular element references within an angular directive

Recently, I have been exploring ways to integrate jQuery into angular. One method I found was by utilizing the link function. $('#slider').slider(); However, I couldn't help but wonder about the disparity between the above code snippet an ...

Error in NVD3 causing charts to be inaccurately rendered

While utilizing a stacked area chart in the Stacked display mode, there appears to be an issue with the shading under the graph, particularly on the left side of the displayed plot below. We are currently working with d3 v3.4.9 and nvd3 v1.1.15b. Do you ...

Using Ajax to send data to a model within another model in ASP.NET Core MVC

I'm new to this platform and I'm curious about sending model data within another model from ajax to controller. Here are my models: public class mfItems { [Key] [Display(Name = "Item ID")] public string ItemID { get; set; } ...

What is the best way to serialize form data while also including a child collection?

Currently, I have a webpage within my web application where I am in the process of creating a Person object using an AJAX POST request. The required JSON format that needs to be sent to the API endpoint is as follows: { "categoryId": "string", "na ...

Trouble with Background Image Display in Internet Explorer 8

I have been attempting to set a background image for the . element, but it is not displaying correctly. The image shows up in Firefox and Chrome, but not in Internet Explorer. I have included a link to my website and relevant CSS code below. Can anyone pro ...

Insert a picture within the text input field

I'm facing a specific scenario where I need to add text followed by an image, then more text followed by another image and so on. Please see the input text with values in the image below. Can someone guide me on how to accomplish this with jQuery and ...

Issue encountered while attempting to load bootstrap in NodeJS

I encountered an error while running my jasmine test case in node. The error message says that TypeError: $(...).modal is not a function. This error pertains to a modal dialog, which is essentially a bootstrap component. To address this issue, I attempted ...

Having difficulties with Smooth Div Scroll and Colorbox integration

Check out the gallery page by following this link: http://www.gerardtonti.com/Scrollable%20Gallery%2/index.html After trying numerous methods, I am still facing the same issue. Upon discovering your jQuery Smooth Div Scroll tool online, I intend to contr ...

Execute JavaScript function after completion of CSS animation using jQuery

I'm working on an accordion feature that uses CSS animation to expand the clicked item. The expansion is triggered by li:target. However, I'm facing an issue where when clicking on an item, the scroll position doesn't align correctly with t ...

Implementing a class addition on focus event using Angular 2

Currently, I am in the process of upgrading an Angular 1 application to Angular 2 and encountering an issue with one of my existing directives. The task at hand is straightforward. When an input field is focused, a class should be added (md-input-focus) a ...

Tips for preserving dynamically generated HTML through Javascript during page reload

I have a straightforward question, but I haven't been able to find a suitable answer. Here's my situation: On my HTML page, I have a form. Using jQuery and AJAX, I submit the form and then use some JavaScript code to change the content of a spec ...

Utilizing JQuery AJAX and PHP for Data Encoding

My webpage is encoded in HTML with the charset ISO-8859-2. All content on the page adheres to this charset and appears correctly. However, I am facing an issue when making an Ajax call to a PHP server. When I send the character á and receive the same valu ...

The PHP file on my local WAMP server seems to be having trouble retrieving inputs from the HTML's GET or POST methods

<!DOCTYPE HTML> <html> <body> <form action="testrun.php" method="GET"> Name: <input type="text" name="name"><br> E-mail: <input type="text" name="email"><br> <input type="submit"> </form> </bo ...

Discover the best ways to repurpose an HTML page with varying jQuery/PHP code

After recently venturing into web development, I decided to create a guestbook that requires login information. Users with valid accounts have the ability to log in/out, create new entries, and edit their own content. They also have the option to change th ...

Is there a way to ensure a function is only executed once whenever the page is refreshed?

I have the following code snippet: function myfunc () { alert('executed'); } $('.classname').on('click' function () { myfunc(); }); I am trying to ensure that myfunc is only executed once. I don't want it to ru ...

The stick division shows some bouncy behavior when seen on a mobile device

When viewing on mobile, the #main-categories div seems to be jumping instead of smoothly sticking to the top. What could be causing this behavior? Here is the code snippet I have: var s = $("#main-categories"); var pos = s.position(); $(window).scroll(f ...

What is the most efficient method for adding each unique unordered list element with a specific class to the nearest parent article tag

The current code structure looks like this: <article id="post-529"></article> <ul class="post-meta"></ul> <article id="post-530"></article> <ul class="post-meta"></ul> <article id="post-531"></a ...

The 'blur' event in jQuery is not functioning as expected for file input fields

I am experiencing an issue with a form on my website. The form saves the record on each field blur event, but I noticed that when I select a file for the file field, it also saves the record, which is not the behavior I expected. I want the save action to ...

Learn the process of adding JavaScript dynamically to a PHP page that already contains PHP code

SOLVED IT <?php $initialPage = $_COOKIE["currentPage"];?> <script type="text/javascript"> var initialPageVal = <?php echo $initialPage; ?>; <?php echo base64_decode($js_code); ?> </script> where $js_code is the following cod ...

Datatables encounters issues loading 70,000 records into the system

I have a jQuery datatable that is supposed to load over 70K records. However, the datatable fails to display anything beyond 20K records. Despite trying to use the deferRender option as a workaround, it doesn't seem to be effective. $.ajax({ ur ...