i have this form action:
<form action="https://google.com">
<input type="text" required>
<input type="submit" onclick="mostra(this, form)">
</form>
<script>
function mostra(that, form) {
if (form.checkValidity()) {
if (confirm('Sei sicuro di inviare la richiesta?')) {
that.disabled = true;
that.value = 'porca madonna';
form.submit();
} else {
alert("else");
return false;
}
}
}
</script>
When the pop up of the confirm()
method comes out and i click cancel
, the flow of the code correctly enter in the else, but the form is sent anyway.
I tried to use <input type="button" onclick="mostra(this,form)">
and it works correctly, so the flow it’s different between ok and cancel
, but the popup of the of the HTML required
prorperty if the input is empy is never showed. Here, i understand that it’s because the form need to be submitted and not just "clicked".
So i think that the first code is better. How i can solve my problem and have the correct flow?
Thank you
2
Answers
Prevent the
submit
event instead of returning false onclick
The button type "Submit" is inside a form and when the form is submitted the page is reloaded. You need cancel the default action of the event with the preventDefault() method.