nickjyc
nickjyc

Reputation: 128

Get form onsubmit to return true from addEventListener function

Here's the problem. I have a form with various inputs and a submit button. When the user hits "submit", it waits for an "addEventListener" event to fire (usually within 3 seconds). I need the form to then properly submit the form (preferably without using AJAX).

$('#form').submit(function(){
    var ele=document.getElementById('audio');
    ele.addEventListener('canplay',function(){
        // After doing some stuff here, how do I get the parent function to
        // return true so that the form can be submitted?
    });
    // I put this here so that the browser is forced to wait for the
    // "addEventListener" event
    return false;
});

Upvotes: 0

Views: 651

Answers (1)

gilly3
gilly3

Reputation: 91527

Store a boolean variable that indicates whether or not to submit the form. Set it to true from the canplay handler:

(function () {
    var shouldSubmit = false;
    $('#form').submit(function(){ 
        var ele=document.getElementById('audio'); 
        ele.addEventListener('canplay',function(){ 
            // do some stuff here
            shouldSubmit = true;
        }); 
        return shouldSubmit; 
    }); 
})();

This will cause that after the canplay event has fired, the form can be submitted. If you want the form to be submitted immediately when the canplay event fires, call form.submit() instead:

$('#form').submit(function(){ 
    var ele=document.getElementById('audio'); 
    var form = this;
    ele.addEventListener('canplay',function(){ 
        // do some stuff here
        form.submit();
    }); 
    return false; 
}); 

Upvotes: 1

Related Questions