In my form I have two radio buttons and the page has a script which validates the form itself, up until the radio buttons. So if you fulfill all the criteria prior to the radio buttons you will be able to submit the form, so naturally I want to make sure the user selects an option before the form can be submitted.
I have found a function which does this here: Radio button validation in javascript
I have adapted the script from the top answer to fit to my current script but it won't work. It will either crash, or display the error but then still go to the submission page.
I have tried doing the complete opposite of how the answer tests for arguments since the answer uses var formValid = false;
and I use valid = true;
.
I have commented out the radio button check part of the function and returned it to the default arguments (and cleaned up the answer's bad use of braces).
function checkForm() {
var valid = true;
var radios = document.getElementsByName(smoking);
if (!retext.test(document.myform.textfield.value)) {
document.myform.textfield.style.border = 3.5px solid red;
document.getElementById(text).innerHTML = Invalid text.;
document.getElementById(text).style.display = block;
valid = false;
}
if (!re.test(document.myform.email.value)) {
document.myform.email.style.border = 3.5px solid red;
document.getElementById(emailwarn).innerHTML = Invalid email.;
document.getElementById(emailwarn).style.display = block;
valid = false;
}
if (!retel.test(document.myform.tel.value)) {
document.myform.tel.style.border = 3.5px solid red;
document.getElementById(telwarn).innerHTML = Invalid telephone number.;
document.getElementById(telwarn).style.display = block;
valid = false;
}
/*var i = 0;
while (!valid && i < radios.length) {
if (radios[i].checked) {
valid = true;
}
i++;
}
if (!valid) {
document.getElementById(radiowarn).innerHTML = Please select one.;
document.getElementById(radiowarn).style.display = block;
}*/
return valid;
}
<form name=myform method=POST action=http://manutd.com onsubmit=return checkForm()>
<fieldset>
<legend>Hi</legend>
<label>Random text: </label>
<input type=text name=textfield>
<div id=text></div>
<label>Email: </label>
<input type=email name=email>
<div id=emailwarn></div>
<label>Tel: </label>
<input type=tel name=tel maxlength=11>
<div id=telwarn></div>
<label>Smoking: </label>
<input type=radio name=smoking value=1>
<label>Non-smoking: </label>
<input type=radio name=smoking value=2>
<div id=radiowarn></div>
<input type=submit value=Submit Form>
<input type=reset value=Reset Form>
</fieldset>
</form>