简体   繁体   中英

How can I validate this radio button?

How can I validate the radio field? It must be checked, if not checked, I would either like a err_radio441 to show up or an alert. I read some posts about checked but I am pulling from name because I know ID won't work. I am missing .checked or something. Any Help would be appreciated!

function validateForm()  {
    var primaryfullname=document.getElementById('primaryfullname').value.trim();
    var birthdate=document.getElementById('birthdate').value.trim();
    var radio441=document.getElementByName('radio441').value.trim();

var count=0;

 if (primaryfullname.length==0)  {
     document.getElementById("err_primaryfullname").innerHTML="<br><span class='errorbar'>*You must enter a primary name</span>";
            } else {
    count++; 
    document.getElementById("err_primaryfullname").innerHTML="";
   }



  if (birthdate.length==0)   {
     document.getElementById("err_birthdate").innerHTML="<br><span class='errorbar'>*You must enter a primary birth date</span>";
            } else {
    count++; 
    document.getElementById("err_birthdate").innerHTML="";
   }



 if (radio441.length==0)  {   
     document.getElementById("err_radio441").innerHTML="<br><span class='errorbar'>*You must select a gender</span>";
            }  else  {
     count++; 
     document.getElementById("err_radio441").innerHTML="";
   }

 if (count==3)
     {
      return true;
      } else {
      return false;
      }

} // End Validation Function

Try using this:

var radio441 = document.getElementsByName('radio441');

// your other code

function checkRadio(elem){
    for (var i = 0; i < elem.length; i++) {
        if(elem[i].checked) return true;      
    }
    return false;
}

if (!checkRadio(radio441)){
     document.getElementById("err_radio441").innerHTML="<br><span class='errorbar'>*You must select a gender</span>";
} else {
    count++; 
    document.getElementById("err_radio441").innerHTML="";
}

It loops through each radio button and returns true if any one of them is checked and false if none are.

if (!radio441.checked) {
   // The radiobutton is not checked
} else {
   // The radiobutton is checked
}

EDIT
To get the element by name you have to use document.getElementsByName('radio441')[0] , assuming there's only one element with that name.

var radio441 = document.getElementsByName('radio441')[0];
if (!radio441.checked) {
   // The radiobutton is not checked
} else {
   // The radiobutton is checked
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM