简体   繁体   中英

Inline onclick is overriding JQuery click()

A follow on from this question

Edit

JSFiddle code

As you can see if you run the code the button text does not change, the onclick is overriding the click function. If you remove the form id attribute from the function and the onclick attribute from the html tag the code works as expected (in a real scenario no onclick function implies a submit button rather than a button)

End Edit

I had thought that a typo was responsible for JQuery not firing the click() event when an inline event was specified, however I've run into the issue once more. Here's my code and the offending tag

<input id="submit1" type="button" onclick="this.disabled=true; doSubmit();" value="submit">


<script>myfunction('submit1', 'working', myformID)</script>

var myfunction = function(ID , text , formID) {
if(ID) {
    var element = document.getElementById(ID);
    if(formID) {
        var form = document.getElementById(formID);
    }
    if (element) {
        jQuery(element).click( function() {
            if(jQuery(this).attr('disabled')) {
                return false;
            }
            jQuery(this).attr('disabled' , 'disabled');
            jQuery(this).attr('value' , processingText);
            onclick = (jQuery(this).attr('onclick') || jQuery(this).attr('onClick'));
            if(form && !onclick) {
                jQuery(form).submit();
            } 
            jQuery(this).click();
        });
    }
}
};

I'm using javascript to create a function which will disable submit buttons while keeping any onclick attribute working in case of a doSubmit, like in this case. In other cases where the form id is set and there isn't an existing onclick I submit the form. Therefore if there is an issue with the html tag I need a general way to fix it with JS.

Many thanks in advance

Your inline handler disables the button: this.disabled=true;

Then jQuery handler checks if it is disabled and returns if so:

if(jQuery(this).attr('disabled')) {
      return false;
}

There is, unfortunately, no way to predict the order of event handlers execution for the same event on the same element.

As a quick fix, I can suggest this:

Demo

jQuery(element).click( function() {
    if(jQuery(this).attr('disabled-by-jquery')) {
        return false;
    }
    jQuery(this).attr('disabled' , 'disabled');
    jQuery(this).attr('disabled-by-jquery' , 'disabled');
    jQuery(this).attr('value' , text);
    onclick = (jQuery(this).attr('onclick') || jQuery(this).attr('onClick'));
    if(form && !onclick) {
        jQuery(form).submit();
    } 
    jQuery(this).click();
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM