0

I have my html page with a form that, onsubmit call a javascript function for check some value:

html:

<form onsubmit="isempty();" role="form">

isempty():

function isempty() {
    var r_1;
    var r_2;
    var r_3;


    r_1 = document.getElementById("t_select");
    r_2 = document.getElementById("t_descr");
    r_3 = document.getElementById("t_terms");

    if((r_1.value == "Please select...") || (r_2.value == "") || (r_3.checked == false)) {
        alert("Please fill in all the form fields including the terms of use to proceed with the publication");
        return false;
    } else {
        //OK
    }

}

All works done, the only problem is that in case of check fail, page display alert then reload, cleaning all preview inserted data. How can I display alert in case of failure and then freeze page (no reload)?

So many thanks in advance

Charlie
  • 22,886
  • 11
  • 59
  • 90
Manuel Santi
  • 1,106
  • 17
  • 46
  • You might want to check this one: https://stackoverflow.com/questions/4227043/how-do-i-cancel-form-submission-in-submit-button-onclick-event – AarónBC. Jun 15 '19 at 05:54
  • 1
    Possible duplicate of [JavaScript code to stop form submission](https://stackoverflow.com/questions/8664486/javascript-code-to-stop-form-submission) – Charlie Jun 15 '19 at 06:01

2 Answers2

2

You should return a value in the onSubmit event to control the submission.

<form onsubmit="return isempty();" role="form">

And let the function return true or false to do the controlling.

Charlie
  • 22,886
  • 11
  • 59
  • 90
1

take the event argument use it to prevent the default behavior of the browser in this case you'll not loose your data

 isEmpty(event) {
   event.preventDefault()
   // do whatever you were to do now
}
Gene Rally
  • 19
  • 3