8 Replies - 5344 Views - Last Post: 26 March 2012 - 04:38 AM

#1 codine24/7  Icon User is offline

  • D.I.C Head

Reputation: 0
  • View blog
  • Posts: 54
  • Joined: 12-February 12

Form Validation with Radio Buttons

Posted 24 March 2012 - 11:55 PM

I am new to Javascript and would like to do some client side validation before
this page is sent to my servlet for more validation! but i can not figure
out how to iterate through my testForm
<%@page import="data.Question"%>
<%@page import="data.Test"%>
<%@page import="java.util.ArrayList"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Test</title>
        <script type="text/javascript">
            function validate(){
                for(var i=0;i<5;i++){
                    var x=document.testForm.question+i;
                    if(x==null || x==""){
                        document.getElementById("unAnswered").innerHTML
                        ="<span style=\"color:red\">You must answer all questions</span>";
                        return false;
                    }
                }
            }
        </script>
    </head>
    <body>
        <form name="testForm"action="gradeTest" method="post" onsubmit="return validate()">
    <%Test test= (Test) request.getAttribute("test");
    if(test==null){
        response.sendRedirect("Home");
    }
    int i=1;
        for(Question q: test.questions){%>
            
                <p><%=q.getQuestion()%></p>
                <%for (String a: q.answers){%>
                    <%=a%><input type="radio" name="question<%=i%>" value="<%=a%>" />
                <%}%>
            
    <%i++;}%>
            <br /><br /><input type="submit" value="submit test" />
        </form>
            <div id="unAnswered"></div>
    </body>
</html>





The output is a simple test i made up. I would really appreciate it if somebody could
help me with my validation method.

heres the output








<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Test</title>
        <script type="text/javascript">
            function validate(){
                for(var i=0;i<4;i++){
                    var x=document.testForm.question+i;
                    if(x==null || x==""){
                        document.getElementById("unAnswered").innerHTML
                        ="<span style=\"color:red\">You must answer all questions</span>";
                        return false;
                    }
                }
            }
        </script>
    </head>
    <body>
        <form name="testForm"action="gradeTest" method="post" onsubmit="return validate()">
    
            
                <p>What is the largest state</p>
                
                    California<input type="radio" name="question1" value="California" />
                
                    Alaska<input type="radio" name="question1" value="Alaska" />
                
                    Texas<input type="radio" name="question1" value="Texas" />
                
            
    
            
                <p>Who is the founding father of America</p>
                
                    Abraham<input type="radio" name="question2" value="Abraham" />
                
                    George Washington<input type="radio" name="question2" value="George Washington" />
                
                    Theodore Rosevelt<input type="radio" name="question2" value="Theodore Rosevelt" />
                
            
    
            
                <p>asnwer: 6+4/8</p>
                
                    6.5<input type="radio" name="question3" value="6.5" />
                
                    5/4<input type="radio" name="question3" value="5/4" />
                
                    6.125<input type="radio" name="question3" value="6.125" />
                
            
    
            
                <p>Who are you voting for is 2012</p>
                
                    Mit Romney<input type="radio" name="question4" value="Mit Romney" />
                
                    Donald Trump<input type="radio" name="question4" value="Donald Trump" />
                
                    Barack<input type="radio" name="question4" value="Barack" />
                
                    None of the above<input type="radio" name="question4" value="None of the above" />
                
            
    
            
                <p>Who sucks more</p>
                
                    Teabow<input type="radio" name="question5" value="Teabow" />
                
                    Manning<input type="radio" name="question5" value="Manning" />
                
                    Sanchez<input type="radio" name="question5" value="Sanchez" />
                
                    All of the above<input type="radio" name="question5" value="All of the above" />
                
            
    
            <br /><br /><input type="submit" value="submit test" />
        </form>
            <div id="unAnswered"></div>
    </body>
</html>



if someone could provide a way to iterate through with a for each loop instead of
a controlled for loop that would be awesome! At the very least help with my if
statement would be amazing!

Is This A Good Question/Topic? 0
  • +

Replies To: Form Validation with Radio Buttons

#2 hiddenghost  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 39
  • View blog
  • Posts: 621
  • Joined: 15-December 09

Re: Form Validation with Radio Buttons

Posted 25 March 2012 - 12:52 AM

So far so good.
          function validate(){
	                for(var i=0;i<4;i++){

It would be better for clarification purposes to put the declaration of the variable with var outside the for.
If you do that you should make sure to declare with var inside the function to retain scope.
function(){
    var i;
    for(i=0;i<4;i++) // instead
}

Here you have test.Form.question. That's ok.
               var x=document.testForm.question+i;

You should have something more like:
document.getElementsByName("question+i")

to get directly to the node.

You have a check for null or an empty string.
	                    if(x==null || x==""){

When this code goes the line:

	                        document.getElementById("unAnswered").innerHTML
	                        ="<span style=\"color:red\">You must answer all questions</span>";


Should be run in the page before the page changes(like during a submission which makes the page reload or load a different page).
It would probably be better to use onclick for this instead of onsubmit.
	                        return false;	                    }
	                }
	            }

You might not need to return anything.
Instead of returning false you probably should to the onclick when they click the submit button.
Then use javascript to submit the form if the check passes like:
for(i=0;i<5;i++){
    if(x==null || x==""){
    // do code when false and display message: You must answer all questions
    // Here we do not submit the code, but 
    // instead we calculate all truths
    }
}
// after the loop for the above check
if(i == 4){ // check if loop finished and if so all radios require are chosen
    // do code when true and submit the form
}


Here's a page about submitting a form with javascript.
http://www.javascrip...rm-submit.phtml

The loop will do the message more than once but you only need the message once so I'll leave that up to you to decide if the overhead of processing the same message more than once is acceptable.

An even more refined way would be to:
// onclick initiates this
for(i=0;i<5;i++){
    if(x == false){ break; }
}
if(i == 4){
    // submit forum
}else{
    // display message
}


This post has been edited by Dormilich: 25 March 2012 - 01:13 PM

Was This Post Helpful? 1
  • +
  • -

#3 Dormilich  Icon User is offline

  • 痛覚残留
  • member icon

Reputation: 3541
  • View blog
  • Posts: 10,236
  • Joined: 08-June 10

Re: Form Validation with Radio Buttons

Posted 25 March 2012 - 02:30 AM

View Posthiddenghost, on 25 March 2012 - 08:52 AM, said:

So far so good.
          function validate(){
	                for(var i=0;i<4;i++){

Except you shouldn't use var inside the for.
var i;
for(i=0;i<4;i++) // instead

though you have to declare it as local variable then. otherwise you create a global variable with a high potential of side effect.
          function validate(){
	                var i;
	                for(i=0;i<4;i++){

personally I see no reason not to use var in the for() loop.

This post has been edited by Dormilich: 25 March 2012 - 09:13 AM

Was This Post Helpful? 2
  • +
  • -

#4 hiddenghost  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 39
  • View blog
  • Posts: 621
  • Joined: 15-December 09

Re: Form Validation with Radio Buttons

Posted 25 March 2012 - 11:29 AM

View PostDormilich, on 25 March 2012 - 04:30 AM, said:

though you have to declare it as local variable then. otherwise you create a global variable with a high potential of side effect.
          function validate(){
	                var i;
	                for(i=0;i<4;i++){

Ya I didn't really emphasize that. Thanks Dormilich

View PostDormilich, on 25 March 2012 - 04:30 AM, said:

personally I see no reason not to use var in the for() loop.

Oh. Yes. I am in C programming mode.
It's what I do for readability and clarification of what's happening with the variables.
There certainly isn't an explicit need.
Like the code wouldn't break if it was in there.
Post edited for clarification.
Was This Post Helpful? 0
  • +
  • -

#5 Dormilich  Icon User is offline

  • 痛覚残留
  • member icon

Reputation: 3541
  • View blog
  • Posts: 10,236
  • Joined: 08-June 10

Re: Form Validation with Radio Buttons

Posted 25 March 2012 - 01:16 PM

sometimes I even go as far as (esp. if the loop direction does not matter)
for (var i = list.length; i--;)/> {
    // do something with list[i]
}

Was This Post Helpful? 0
  • +
  • -

#6 codine24/7  Icon User is offline

  • D.I.C Head

Reputation: 0
  • View blog
  • Posts: 54
  • Joined: 12-February 12

Re: Form Validation with Radio Buttons

Posted 25 March 2012 - 02:50 PM

View PostDormilich, on 25 March 2012 - 01:16 PM, said:

sometimes I even go as far as (esp. if the loop direction does not matter)
for (var i = list.length; i--;)/> {
    // do something with list[i]
}


Well this is what i came up with. It works but if instead of i<5 would i be able
find the total number of questions i have on the page? i was thinking of maybe
creating a div tag for each question and each id will increment.
kind of like my name value in inputs in my radio buttons. If you have a better
idea or if this is a bad idea i would appreciate the advice, i am still new to java script!

function validate(){
       for(var i=1;i<=5;i++){
                    var answer=false;
                    var t=""+i;//type casting i
                    var q="question"+t;//appending number
                    var x=document.getElementsByName(q);//getting those radio groups
                    var len=x.length;
                    for(var p=0;p<len;p++){
                        if(x[p].checked){
                            answer=true; 
                        }
                    }
                    if(!answer){
                        document.getElementById("unAnswered").innerHTML
                            ="<span style=\"color:red\">You must answer all questions</span>";
                        return false;//exit if one is not answered
                    }
                }
                document.forms["testForm"].submit();//by here all questions are answered
            }

Was This Post Helpful? 0
  • +
  • -

#7 Dormilich  Icon User is offline

  • 痛覚残留
  • member icon

Reputation: 3541
  • View blog
  • Posts: 10,236
  • Joined: 08-June 10

Re: Form Validation with Radio Buttons

Posted 25 March 2012 - 03:06 PM

there is no need for line #4, JS will always do an implicit type cast, if necessary (that is, line #5 will also work if i were a number).

This post has been edited by Dormilich: 25 March 2012 - 03:15 PM

Was This Post Helpful? 0
  • +
  • -

#8 hiddenghost  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 39
  • View blog
  • Posts: 621
  • Joined: 15-December 09

Re: Form Validation with Radio Buttons

Posted 26 March 2012 - 04:17 AM

View PostDormilich, on 25 March 2012 - 03:16 PM, said:

sometimes I even go as far as (esp. if the loop direction does not matter)
for (var i = list.length; i--;)/> {
    // do something with list[i]
}

Well that certainly would make less lines of code.
Was This Post Helpful? 0
  • +
  • -

#9 Dormilich  Icon User is offline

  • 痛覚残留
  • member icon

Reputation: 3541
  • View blog
  • Posts: 10,236
  • Joined: 08-June 10

Re: Form Validation with Radio Buttons

Posted 26 March 2012 - 04:38 AM

and its faster (does not have a post-cycle statement) and is safer with regards to live lists (if you delete from a live list (e.g. HTMLCollection, NodeList) the indices are reassigned, so your fixed final loop-index may be higher than the last index of the actual list and, alternately, if you recalculate the list length before each cycle, adding to the list will catch you in an infinite loop)
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1