Odd Behavior when altering button attribute using Jquery

After disabling a button with a click handler, I have noticed an interesting behavior where the button does not submit afterwards. The issue seems to vary between different browsers, with Firefox still allowing form submission after the button is disabled, while Chrome and IE block it.

<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js">
    </script>
    <script>
        $(function(){
            $("#btn").on("click",function(){

                $(this).prop('disabled','true');
                alert('clicked');
            });



            $("#frm").on("submit",function(){
                alert("submit1");

            });

            $("#frm").on("submit",function(){
                alert("submit2");
            });

        })
    </script>
</head>

<body>
    <form id="frm" action="#">
        <input type='submit' id="btn"/>
    </form>
</body>

It's puzzling that the submit action is being prevented when the button is disabled. What could be causing this strange behavior? In Chrome and IE, the sequence of events is triggering the click first and then immediately closing the script.

Why isn't it following the expected order of execution: clicking the button first, followed by submitting the form?

Answer №1

It seems like what you're trying to convey is that disabling the submit button upon clicking prevents the form from being submitted, which is not the desired outcome.

The issue lies in the fact that the click event occurs before the button's activation behavior, which is essentially what the button is supposed to do according to the HTML5 specification. By disabling the button before the browser determines its activation behavior (which occurs after all click handlers have been executed), the form submission does not take place as intended. According to the spec, a disabled submit button lacks activation behavior and therefore does not trigger form submission.

This raises the question of when exactly the browser decides on the activation behavior- before or after the click handlers are run. Referring to the DOM Events spec reveals that the click event happens first, followed by the activation behavior. It appears Chrome makes this decision after the click event, while Firefox may make it before the event completes.

As a practical solution, delaying the disablement of the button very briefly within the click handler ensures that the form submission still takes place:

$("#btn").on("click",function(){
    var btn = this;

    setTimeout(function() {
        btn.disabled = true;
    }, 0);
    alert('clicked');
});

Live Example | Source


On a separate note, in the above example, I've simplified the code by using this.disabled = true; instead of $(this).prop("disabled", true");. There's no need to wrap the element in jQuery just to set a basic property value.

Answer №2

Here is a solution that may resolve your problem:

$("#btn").on("click", function (event) {
        event.preventDefault();
        $(this).prop('disabled', true).closest('form').submit();
        //to submit FORM without firing jquery's attached handlers
        //$(this).prop('disabled', true).closest('form').get(0).submit();
        alert('clicked');
    });

Check out the DEMO here

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

Easily upload a file by simply selecting it, no need to fill out a form or submit anything

I am working on adding a mail feature to a WordPress admin plugin. My goal is to allow users to attach a file dynamically and send it through email as an attachment. I have implemented an AJAX method for choosing the file upload, but I seem to be stuck. Ca ...

Discover a specific segment of the pie chart

Currently, I have a pie chart that has been created using HTML5 canvas. I am able to retrieve the coordinates (X,Y) when the mouse hovers over it. Now, my goal is to determine which slice of the pie chart the Point (X,Y) falls into. Please note: I have ...

What is the process for saving an HTML document with SaveFile.js?

I'm currently implementing a save feature for my website. Utilizing the 'SaveFile.js' module from this link: 'https://github.com/eligrey/FileSaver.js/' Once the user clicks on the save button, the goal is to have the entire documen ...

What causes Bootstrap to malfunction when the route contains double slashes?

When using /something, everything works fine, but when switching to /something/somethingelse, Bootstrap fails to function. It seems that the number of "/" characters in the route is causing this issue, rather than the content inside the .ejs file. Here is ...

iterating over a list of files using JavaScript

I am currently working on setting up individual ajax requests for each file being uploaded. I have a functioning ajax call that creates a record, returns some html, and provides the tempID of the record which is then used in another ajax call that triggers ...

How to share information between ES6 classes?

Recently, I decided to create a node/express app just for fun. One of the components I built is an ES6 class called 'TwitterClient.es6' that interfaces with the Twitter API to fetch data. Now, in my 'server.es6', which handles the route ...

Substitute all attributes of objects with a different designation

I need to update all object properties from label to text. Given: [ { "value": "45a8", "label": "45A8", "children": [ { "value": "45a8.ba08", "label": "BA08", &q ...

triggers an unexpected error in console.log

I need help with the following code: function printName(obj) { console.log(obj.name); } printName({ name: "myName" }); (function displayError(errorMsg){ console.log(errorMsg); })("Error"); However, when I try to run this code, I am encountering a T ...

The puzzle of Media Queries

I have been searching far and wide for a solution to my issue, which I believe is quite basic. Currently, I am struggling with it mentally. I am in the process of customizing a responsive template. This is uncharted territory for me when it comes to medi ...

Utilize a Vue.js filter on the v-model within an input element

Seeking assistance! I successfully created a directive that wraps the Jasny Bootstrap Plugin, specifically focusing on the input mask feature! Additionally, I have developed a custom filter using moment to format date fields! The date format received fro ...

In Javascript, where are declared classes stored?

When working in a browser environment like Firefox 60+, I've encountered an issue while attempting to retrieve a class from the global window object: class c{}; console.log(window.c); // undefined This is peculiar, as for any other declaration, it w ...

Implementing relative path 'fetch' in NextJs App Router

When attempting to retrieve data using fetch("/api/status"), the URL is only detected when utilizing the absolute path: fetch("http://localhost:3000/api/status"). This is happening without storing the path in a variable. ...

Tips for organizing JSON information in ReactJS

Could someone lend a hand with sorting JSON data in ReactJs? I'm having trouble getting it to work properly. Also, if I want to sort by title, would it be the same process? Thanks! This is what I've tried so far: componentDidMount() { ...

Refresh ng-repeat array after implementing filter in controller

I am currently facing an issue with updating my table view when changing a variable that filters an array. The filter is applied in the controller based on the values of a specific variable called columnFilter. However, the filter does not reapply to updat ...

Steps for revealing all the information from a database when clicking on the 'Read More' button

I recently set up a database called Magazine, featuring a table named social_media. This table consists of 5 columns: ID, Headline, Author, Content Short, Content. The Content Short column contains condensed versions of the articles which are displayed on ...

Combining Repetitive Elements in an Array

Trying to combine an array of products with the same order_id while also including all objects from a second products array. Below are some sample orders: const orders = [ { "order_details": { }, "order_id": "1", ...

Leveraging ng-click and ng-hide/show directives within ng-repeat in Angular

I have a simple Single Page Website built with Angular. I utilized ng-repeat to generate content on the main page, where each item is an image. I am looking to create an alternate view for each image to display more details. I have implemented this feature ...

Creating files for two HTML pages with Vue: A step-by-step guide

Currently, I am working on creating two HTML files as part of my project structure. This is how it looks: |- node_modules |- public | |- blog | | |- some-page.html | |- index.html |- src (contains all the Vue components) |- Blog.Vue |- Index.Vue ...

What is the reason for labels appearing inside select boxes?

Can someone help me understand why my select box label is displaying inside the select box? For example, when I am not using react-material-validator it looks like this: https://codesandbox.io/s/5vr4xp8854 When I try to validate my select box using the r ...

Execute a JavaScript function on a Node server following a click event in an HTML document

Hello everyone, I am currently working on a project using node.js in a Windows environment. With the help of the express module, I am trying to create a static page that includes a Submit form. When someone clicks the "Submit" button, I intend to execute a ...