Jump to content

[SOLVED] Radio Button Check


dizzy1

Recommended Posts

Hi All,

 

My script only works if thier is more than 1 radio option, i need it to work no matter how many radio options thier are.

 

Javascript

<script language="JavaScript" type="text/javascript">
<!--
function checkTest(form)  
{ 
  var checked = false; 
  var buttons = form.elements.TestRadioOption; 
  
   
  
  for (var i=0; i<buttons.length; i++)  
  {  
    if (buttons[i].checked) {  
      checked = true; 
      break;  
    }  
  }   
  
   if(checked == false) {
     alert("Please Select a Radio BUtton");  
   }
   
   return checked ;    
}	
//-->
</script>

 

 

HTML

 

<form action="Test.php" method="post" onsubmit="return checkTest(this);"> 

<p>Option 1 <input type="radio" name="TestRadioOption" value="1"></p> 

<input  type="submit" value="submit">
<form>

 

 

Link to comment
https://forums.phpfreaks.com/topic/152178-solved-radio-button-check/
Share on other sites

The problem is that a radio group of multiple options is treated as an array, whereas a group with just one option is not an array. Therefore the for() loop fails due to the fact that buttons.length has no value. The solution is to check if buttons.length is a valid parameter.

 

Try this

function checkTest(form)  
{ 
  var checked = false; 
  var buttons = form.elements.TestRadioOption; 

  if (buttons.length)
  {
    //Array: iterate through each option
    for (var i=0; i<buttons.length; i++)  
    {  
      if (buttons[i].checked) { return true; }  
    }
  }
  else
  {
    //Not an array Array: check the single value
    checked = buttons.checked;
  }
  
  if(checked == false)
  {
    alert("Please Select a Radio BUtton");  
  }
   
  return checked;
}

CHEERS, I knew what the problem was didnt know how to go about fixing it, i was trying to see if i could check what the value of buttons.length was and if was less than 0 do something but it didnt work.

 

This was just what i needed but i just had to change it so checked = true instead of just returning true.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.