Karl Karl - 1 year ago 53
jQuery Question

Stop onclick method running with jQuery

I have a button similar to below

<button id="uniqueId" onclick="runMethod(this)">Submit</button>

What I'm trying to do is stop the runMethod from running, until after I've done a check of my own. I've tried using the
function, but this doesn't seem to have worked. Here's my jQuery:

$j(document).on('click', '#uniqueId', function(event) {
if(condition == true) {
// continue...
} else {
return false;

return false;

basically validates the form, then triggers a submit.


What you want to do, especially in the way that you want to do it, requires a some sort of workaround that will always be a bit fiddly. It is a better idea to change the way the button behaves (e.g. handle the whole of the click event on the inside of the jQuery click() function or something along those lines). However I have found sort of a solution for your problem, based on the assumption that your user will first hover over the button. I am sure you can extend that functionality to the keyboard's Tab event, but maybe it will not work perfectly for mobile devices' touch input. So, bear in mind the following solution is a semi-complete workaround for your problem:

    var methodToRun = "runMethod(this)";    // Store the value of the onclick attribute of your button.
    var condition = false;                  // Suppose it is enabled at first.
        // Check your stuff here
        condition = !condition;     // This will change to both true and false as your hover in and out of the button.
        console.log(condition);     // Log the condition's value.
        if(condition == true){      
            $('#uniqueId').attr('onclick',methodToRun); // Enable the button's event before the click.
        console.log('inactive');    // When you stop hovering over the button, it will log this.
        $('#uniqueId').attr('onclick',null);    // Disable the on click event.

What this does is it uses the hover event to trigger your checking logic and when the user finally clicks on the button, the button is enabled if the logic was correct, otherwise it does not do anything. Try it live on this fiddle.

P.S.: Convert $ to $j as necessary to adapt this.

P.S.2: Use the Javascript console to check how the fiddle works as it will not change anything on the page by itself.