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();
}
}
Wilest
  • 1,820
  • 7
  • 36
  • 62

3 Answers3

1

You need to add

e.preventDefault();

for avoiding the default behavior.

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

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.

YogaV
  • 21
  • 2
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;
}
}
john Smith
  • 17,409
  • 11
  • 76
  • 117
  • 1
    Without jQuery: http://stackoverflow.com/questions/10575273/cross-browser-preventdefault-without-jquery – Shautieh Oct 08 '14 at 09:38
  • Thank you so much for putting me in the right direction! After struggling a bit and researching this is what worked:
    and then the javascript:
    – Wilest Oct 08 '14 at 10:28