preventDefault does not work

4

At the following form :

<form id="form_id" method="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" autocomplete="off" onsubmit="valida_form()">

I have a function that checks for blanks:

function valida_form(evt)
{   Array.from(document.getElementById("form_id")).forEach(function(element,index)
    {   if(element.value === "")
        {   form_err++;
        }
    });
    if(form_err > 0)
    {   alert("Há erros:"+form_err);
        evt.preventDefault();
    }else
    {   alert("Sem erro"+form_err);
    }
}

meanwhile form is still being sent.

I'm learning the passage of arguments, and callbacks so if the error is something related, I appreciate the explanation.

    
asked by anonymous 19.07.2017 / 17:48

1 answer

4

preventDefault does not work when the event listener is set inline in HTML ( onsubmit="..." ). Use addEventListener :

document.getElementById('form_id').addEventListener('submit', valida_form, false);

When you use inline, the function must return false to cancel the default operation. And the inline handler needs to return the result of the function: onsubmit="return funcao()" . There is also the possibility of passing a event global object on the call, as Anderson Carlos Woss commented below. However this is not standard and may not work in all browsers. The most recommended is to use addEventListener itself.

    
19.07.2017 / 18:38