Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript override form onsubmit event not working

I am overriding a form submit event like this:

form.onsubmit = function(event) {
  event.preventDefault();

But when I call submit on the form like this in a separate function:

form.submit();

The onsubmit function is not called and the and the form is posted as usual.

Any thoughts?

Edit:

I am also creating a file input in this form and calling its click event immediately. Would this affect the form submit event?:

if (fileInput && document.createEvent)
{
    var evt = document.createEvent('MouseEvents');
    evt.initEvent('click', true, false);
    fileInput.dispatchEvent(evt);
}

Edit #2:

I am submitting the form by calling the form's submit function after the file input value has changed:

function nameFileLabel(id)
{
    var f = document.getElementById('fileForm' + id);
    var l = document.getElementById("fileText_" + id);
    var i = document.getElementById("fInputId" + id);
    if (i.value != '')
    {
        l.innerHTML = i.value.replace('fakepath', '...');
        var theUploadForm = document.getElementById('fileDiv_' + id);
        theUploadForm.style.visibility = 'visible';
        theUploadForm.style.display = 'block';
        f.submit();
    }
}
like image 932
Xavi Avatar asked Apr 30 '15 11:04

Xavi


People also ask

Why Onsubmit is not being called?

The onsubmit handler is not called, because the form cannot be submitted by any normal means, i.e. the submit event cannot be caused. There is only one submit control, and it is declared as disabled. Save this answer.

Can I use onclick instead of Onsubmit?

They're two completely separate events. onclick events fire when the user uses the mouse to click on something. onsubmit events fire when a form is submitted.

What happens when Onsubmit returns false?

return false cancels the default submit action(stops the submission of form). It means Do nothing . Return the control flow.. It means that do nothing on submit.

Is Onsubmit an event handler?

The JavaScript onsubmit is one of the event handling function used for performing the operations in web based applications.


1 Answers

To prevent the form posting your function must return false.

form.onsubmit = function(event) {
    event.preventDefault();
    return false;
}
like image 150
garryp Avatar answered Oct 06 '22 15:10

garryp