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
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;
}

Link to comment
Share on other sites

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.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.