0

I have a form with some fields on. I am still learning Javascript. When my is submitted it triggers my JS which checks if the fields was submitted and then displays the errors in a which is done through innerhtml. Problem is it only display's the div for a few seconds and then finishes reloading the page and the div is not displayed anymore.

function checkradio() {
chosen = ""
len = document.cv.Radio1.length
for (i = 0; (i<2); i++) {
if (document.cv.Radio1[i].checked) {
chosen = document.cv.Radio1[i].value
}
}
if (chosen == "") {
document.getElementById('error-1').innerHTML = "Please choose a type";
document.getElementById("Radio1").focus();
}
}

3 Answers 3

1

You need to add

e.preventDefault();

for avoiding the default behavior.

Hence, if validation fails, the form won't be submitted.

Sign up to request clarification or add additional context in comments.

Comments

1

please check whether your using normal HTML input element or ASP.NET server element. If your using Server element like then page will send back to server(reloaded) when click on button. the details you gave above is not enough.

Comments

0

you need to prevent the default behaviour if validation fails

you most likely do the validation on submit sth like:

 $('form').submit(function(e){


    check = checkradio() // let your function return true or false
    if(!check){
      e.preventDefault(); // add this to not submit the form
    }

 });

so the form will not submit if the validation fails

your tweaked validate function could look like this :

function checkradio() {
chosen = ""
len = document.cv.Radio1.length
for (i = 0; (i<2); i++) {
if (document.cv.Radio1[i].checked) {
chosen = document.cv.Radio1[i].value
}
}
if (chosen == "") {
document.getElementById('error-1').innerHTML = "Please choose a type";
document.getElementById("Radio1").focus();
return false;
}else {
return true;
}
}

2 Comments

Thank you so much for putting me in the right direction! After struggling a bit and researching this is what worked: <form action="xx.php" method="post" name="cv" onsubmit="return toSubmit();" > and then the javascript: <script type="text/javascript"> function toSubmit(){ check = checkradio(); if(!check) { alert('I will not submit'); return false; } else { return true; } } </script>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.