Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 3 of 3
  1. #1
    New Coder
    Join Date
    Apr 2005
    Posts
    32
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Loop Validation Of Radio Buttons?

    Hi,

    I have a survey with 20 questions, each question has 4 options (radio buttons)...

    I am looking to validate that each question has been answered, and if a question has not been answered alert the user which specific question they need to complete.

    Example Of Question setup:
    Code:
    			
    <h4>Question 1 ..............</h4>
    <input name="q1" type="radio" value="1">
    <input name="q1" type="radio" value="2">
    <input name="q1" type="radio" value="3">
    <input name="q1" type="radio" value="4">	
    			  				
    <h4>Question 2 ..............</h4>
    <input name="q2" type="radio" value="1">
    <input name="q2" type="radio" value="2">
    <input name="q2" type="radio" value="3">
    <input name="q2" type="radio" value="4">
    I have tried a loop similar to this:
    Code:
    for (i=0; i >= 20; i++)
    {
       if (formObject.qi.checked == false) 
       {
       err++;
       message+="\n     -  Question" + i + "must be answered";
       }
    }
    But this does not work.... How do I put the i in if statement, so that it is recognised as the loop parameter, rather than just a i???

    Anyhelp would be great, I just want to make the programming a little better than individually going through each question.

    Thanks....

  • #2
    Senior Coder
    Join Date
    Jul 2004
    Location
    New Zealand
    Posts
    1,315
    Thanks
    0
    Thanked 2 Times in 2 Posts
    Just specify a default value. Easier and works with Javascript disabled.
    Forget style. Code to semantics. Seperate style from structure, and structure from behaviour.
    I code to specs, and test only in Firefox (unless stated otherwise).

  • #3
    Supreme Master coder! glenngv's Avatar
    Join Date
    Jun 2002
    Location
    Philippines
    Posts
    11,048
    Thanks
    0
    Thanked 251 Times in 247 Posts
    But these are survey or quiz-type questions. Setting default values is not appropriate.
    Code:
    function isChecked(radGroup){
      for (var i=0;i<radGroup.length;i++){
        if (radGroup[i].checked) return true;
      }
      return false;
    }
    And then in your validation script:
    Code:
    ...
    for (var i=1; i <= 20; i++)
    {
       if (!isChecked(formObject.elements["q"+i])) 
       {
         err++;
         message+="\n     -  Question" + i + " must be answered";
       }
    }


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •