PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, July 30, 2022

[FIXED] How can I validate this radio button?

 July 30, 2022     checked, forms, javascript, radio-button, validation     No comments   

Issue

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

Solution

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.



Answered By - Joe
Answer Checked By - Cary Denson (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing