Luke Stoward
Luke Stoward

Reputation: 1540

Re-enabling event.preventDefault();

I have been searching for ages for a solution to this problem, I am aware that there is no restore default solution type of thing. However here is my problem.

$('#signInbtn').click(function(event) {
    checkLogInForm(event);
});

this checks the login in fields to confirm they are not left blank, like so:

function checkLogInForm(event) {
    var usernameValid, passwordValid = false;
    checkUsername(usernameValid);
    checkPassword(passwordValid);
    if (!passwordValid || !usernameValid) {
        event.preventDefault();
    } else {
        $('#signInbtn').unbind('submit');
    }
}

However the numerous solutions I have tried never result in the form actually submitting when the else is triggered. Any ideas how I can resume/submit the default behaviour? or even an alternative approach. Thanks for any help!

Upvotes: 1

Views: 1362

Answers (2)

Andrew Luhring
Andrew Luhring

Reputation: 1894

fiddle

One solution would be to evaluate whether the preventDefault action should be applied:

/** 
*      toggle status if preventDefaultStatus is true 
*/
function updateStatus(preventDefaultStatus) {
     return (preventDefaultStatus === true) ? false : true;
}

/** 
*      toggle preventDefault
*/
function toggleDefault(isActive) {

    submitElement.onclick = function(e){

        if(isActive === true){

            e.preventDefault();

        }
    }       
}

/**
*      trigger toggleDefault and updateStatus
*/
function update(){
    toggleDefault(status);
    status = updateStatus(status);
}


exampleButton.onclick = update;


(function(){
    update();
})();

(written in pure javascript to clarify that this applies regardless of whether or not you're using jQuery) In jQuery, you would just replace the onclick handlers with .click(function(e){})

Upvotes: 1

Johan van Zyl
Johan van Zyl

Reputation: 1

Try using the 'submit' event with the form id or form name as the jQuery selector for example:

$('#signInForm').submit(function(event) {
    checkLogInForm(event);
});

Your checkLogInForm(event) method can leave the else statement out if the form should be submitted.

Upvotes: 0

Related Questions