JavaScript - radio button validation

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • sunsolaris2000
    New Member
    • Jan 2012
    • 20

    JavaScript - radio button validation

    A list of courses is displayed and user has to select 1, so I used radio buttons. The course list vary from one student to another.

    If I have more than 1 courses displayed and user selects one, everything is ok, but if I display 1 course, the test is JS seems to not be right...

    Validate if radio button(a course) was checked:


    Code:
    function validate2() {
    				//validate radio buttons(if a course is selected)
    				var n = document.entry2.courses.length;
    				ok = 0;
    				
    				for(var i = 0; i < n; i++){
    					if(document.entry2.courses[i].checked){
    						ok++;
    						break;
    					}
    				}			
    				
    				if((document.entry2.ex.checked == true)||
    				  (document.entry2.sem.checked == true)||
    				  (document.entry2.lab.checked == true)||
    				  (document.entry2.pro.checked == true)){
    					ok++;
    				}
    				
    				if(ok == 2){
    					return true;
    				}else{
    					alert("Please select 1 course and at least 1 activity! ok=" +ok);
    					return false;
    				}				
                }
    Code:
    <form action="Result.jsp" method="post" name="entry2" onSubmit = "return validate2()">
    			      
    			      Please choose a course from the ones
    			      <br> where student is assigned:<br><br>
    			      
    			   ...............
    			     
    			    <table border="1" cellspacing="1" cellpadding="8" bgcolor= #EBDDE2> 
    		
    			 	<%
    			 	Iterator<String> i = cs.iterator();
    			    String sCourse = null;
    			    
    			 	while(i.hasNext()){
    			 	  sCourse = i.next();	
    				%>
    				
    				<tr>
    				  <td><%= sCourse %><input type= "radio" name= "courses" value="<%= sCourse %>"></td>
    				</tr>
    				
    				<%}%>
    			</table>
    ok is not becoming 1 at the for loop if there is 1 course only
    Thank you!
  • gits
    Recognized Expert Moderator Expert
    • May 2007
    • 5390

    #2
    in case that this one option isn't 'checked' then it will not be counted - or what is the exact problem? can you post the html as it turns out in the browser instead of the jsp-page? may be you want to auto-select the option when there is only one available?

    Comment

    • sunsolaris2000
      New Member
      • Jan 2012
      • 20

      #3


      ok must be 2 for the form to be submitted.
      And I get ok=1 only when I have 1 course.

      Comment

      Working...