dizzy1 Posted April 2, 2009 Share Posted April 2, 2009 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> Quote Link to comment https://forums.phpfreaks.com/topic/152178-solved-radio-button-check/ Share on other sites More sharing options...
Psycho Posted April 2, 2009 Share Posted April 2, 2009 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; } Quote Link to comment https://forums.phpfreaks.com/topic/152178-solved-radio-button-check/#findComment-799216 Share on other sites More sharing options...
dizzy1 Posted April 2, 2009 Author Share Posted April 2, 2009 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. Quote Link to comment https://forums.phpfreaks.com/topic/152178-solved-radio-button-check/#findComment-799328 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.