Solved

Java Script Form Validation: Radio buttons, Check box, Drop downs and conditional validation

Posted on 2007-11-19
11
958 Views
Last Modified: 2008-02-01
I posted a question on validating my form and got the following which works the way I want, thanks.  I know need to know if I have a radio button group, (Field 2)  a check box selection (Field 3) or a drop down (Field 4)... how do I validate that they are not empty.

The second part is that I have a couple of fields that needs to be validated base on the following:

Field 1a - If it is not empty, then Field 1b needs a value as well and not empty.

I would like it to work with the following JavaScript since I can follow it and I guess this is how one is learning it as well.

-------

<script type="text/javascript">
function validate_form ()
      {
             var errors=new Array();
                  
          var f =  document.getElementById("KMKW_1_Health");
             
            if (f.First_Name.value =="")
            {
                  errors.push("Given First Name");
            }
           
            if (f.Preferred_First_Name.value =="")
            {
                   errors.push("Preferred First Name");
            }
           
            if (f.Last_Name.value =="")
            {
                   errors.push("Last Name");
            }
              if(errors.length)
              {
                    alert("Please fill in the following: \n\n"+errors.join("\n"));
            return false;
              }
              return true;
      }
        
</script>

----

Thanks!



0
Comment
Question by:lanivanvuuren
  • 5
  • 4
  • 2
11 Comments
 
LVL 16

Accepted Solution

by:
anoyes earned 400 total points
ID: 20316307
Give these a shot.

For radio button group:
if (f.Field2.value=="") {
  errors.push("Radio button group.");
}

For checkbox:
if (f.Field3.checked==false) {
  errors.push("Check box");
}

For drop down list:
if (f.Field4.selectedIndex==0) {
  errors.push("Drop down list");
}

For 1a not empty validate 1b
if (f.1a.value<>"" && f.1b.value=="") {
  errors.push("Field 1b");
}
0
 
LVL 54

Assisted Solution

by:b0lsc0tt
b0lsc0tt earned 100 total points
ID: 20316807
I can provide script later if you need it; just let me know.  However I wanted to make a quick comment after reading the post above.

To check radios you need to do a loop.  You need to loop through the "collection" of the radios to see if any are checked (e.g. radioElement[i].checked = true; ).  You can't just look for value.  If you want to check if a specific radio has been checked then you could look at its value to see after finding that it was checked.  One thing that can make the "loop" easier is the radios will all start numbered at 0 as Javascript sees them in the collection.  If you have 2 and want to see if the second is checked then just use ...

document.forms[0].radioName[1].checked == true

A checkbox will use a similar method but it could be different in the specifics.  Remember a checkbox doesn't need to "share" the name.  However the basics of checking to see if the element is checked still hold.  The value will always be there as Javascript sees it.  What matters is if the box is checked.

The info for the select list will work if the first item in the list is the default and you don't want it selected.  Otherwise you will need to modify the script.

I hope this general info helps.  If you need specifics then it will help to see the form tag and these elements or form fields.  The specifics will depend on the form.  If you want a good page/site with info on this then look at http://www.quirksmode.org/js/forms.html.

Let me know if you have a question or need more info.

bol
0
 

Author Comment

by:lanivanvuuren
ID: 20319730
Hello,

I'm going to try anoyes' script to see what it does, I basically only need to see if something was selected if it was a required field.  If I still need a loop script for that, please see what you can come up with.

Thanks

Lani
0
 

Author Comment

by:lanivanvuuren
ID: 20320260
Hello again,

I got it to work up until I add the conditional part of the script in.  When I add the first one in, and test it with non of the other fields being populated as well, it basically "looks" like it ignores the whole validation script and go to the next page where one would have gone ones the required fields where filled in.

Here is the script:
- - - - - - - - - -

<script type="text/javascript">
function validate_form ()
      {
          var errors=new Array();
                  
          var f =  document.getElementById("KMKW_1_Health");
             
            if (f.First_Name.value =="")
            {
                  errors.push("Given First Name");
            }
           
            if (f.Preferred_First_Name.value =="")
            {
                   errors.push("Preferred First Name");
            }
           
            if (f.Last_Name.value =="")
            {
                   errors.push("Last Name");
            }
                  
            if (f.Camp_Session.value =="")
            {
                   errors.push("Session");
            }                  
                  
            if (f.Grade.selectedIndex==0)
            {
                   errors.push("this is for the drop down grade");
            }

            if (f.Camper_Home_Phone.value =="")
            {
                   errors.push("Camper Home Phone");
            }            

            if (f.Health_Food_Allergies.value =="")
            {
                   errors.push("Food Allergies");
            }

            if (f.Health_Medicine_Allergies.value =="")
            {
                   errors.push("Medicine Allergies");
            }

            if (f.Health_Other_Allergies.value =="")
            {
                   errors.push("Other Allergies");
            }

            if (f.Health_Emotional_Issues.value =="")
            {
                   errors.push("Emotional Issues");
            }

            if (f.Health_Physical_Restrictions.value =="")
            {
                   errors.push("Physical Restrictions");
            }      

            if (f.Health_Med_1.value<>""&&f.Health_Con_1.value=="")
            {
                   errors.push("Please list condition #1 being treated for.");
            }
 
            if (f.Health_Other_Medical_Conditions.value =="")
            {
                   errors.push("Other Medical Conditions");
            }                  

            if(errors.length)
            {
                   alert("Please fill in the following: \n\n"+errors.join("\n"));
           
            return false;

            }
           
             return true;
      }
        
</script>
0
 
LVL 16

Assisted Solution

by:anoyes
anoyes earned 400 total points
ID: 20320708
By conditional I assume you're referring to the 'if 1a is not empty then be sure 1b is not empty'?

Try this:
if (f.Health_Med_1.value<>"") && (f.Health_Con_1.value=="")
{
   errors.push("Please list condition #1 being treated for.");
}

If that doesn't work, try this:
if (f.Health_Med_1.value!="") && (f.Health_Con_1.value=="")
{
   errors.push("Please list condition #1 being treated for.");
}

I do believe bol is right however with having to loop through checkboxes to see if one's checked.  Forgot about that.
0
How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

 

Author Comment

by:lanivanvuuren
ID: 20320831
Hey there,

Tried both and same result, even though no fields are filled in it goes to the thank you page as though everything was correct.  So I tried the following and it does the same, it must have something to do with this part of the script... ?

--------
<script type="text/javascript">
function validate_form ()
      {
          var errors=new Array();
                  
          var f =  document.getElementById("KMKW_1_Health");
             
            if (f.Health_Med_1.value!="") && (f.Health_Con_1.value=="")
            {
                   errors.push("Please list condition #1 being treated for.");
            }                  

            if(errors.length)
            {
                   alert("Please fill in the following: \n\n"+errors.join("\n"));
           
            return false;

            }
           
             return true;
      }
        
</script>
0
 

Author Comment

by:lanivanvuuren
ID: 20320870
Wait, I think I got it!!!! it needs more ()

  if ((f.Health_Med_1.value!="") && (f.Health_Con_1.value==""))


Got to love the little things in life!
0
 
LVL 54

Expert Comment

by:b0lsc0tt
ID: 20321289
>> Wait, I think I got it!!!! it needs more () <<

Actually not more just parentheses in the right place.  The following should work too and uses fewer parentheses.

  if (f.Health_Med_1.value!="" && f.Health_Con_1.value=="")

The problem was the missing parentheses for the overall If statement.  There is nothing wrong with how you have it above though. :)

Let us know if you still need help with this.  I missed a few posts it seems and didn't bother to look at the details or code since it seems like you may have this going.  I'll be happy to help with whatever you need though so just let me know.

bol
0
 
LVL 54

Expert Comment

by:b0lsc0tt
ID: 20329551
Did you still have a question or need some help with this?  I noticed the B grade.  If you do still need help or have a question then let me know.  I'll be happy to provide whatever I can.  It is nice to have a change to earn the A grade or at least know why it wasn't.  In this case it seems like I provided lots of information that was very complete so the grade is a bit of a puzzle.

Thanks for the fun question.

bol
0
 

Author Comment

by:lanivanvuuren
ID: 20329819
Hello,

I would like to explain.  When I look at answers while looking for information, I usually go to the "solution" pick.  With this, the solution was WITH help in the end mine.  

Now the problem is this, I felt since you gave me good information too that I would like to give you some of the points as well as for the other person.  When doing that you don't have an option (unless I'm mistaken) to grade each answer you give points to.

I usually give "A" but lately somebody told me not to give it unless you got your question answered 100% or got an answer like that in the end. Which only after I got to my part did I get it from you.

So if there is away I would give you and excellent but since I had to do an overall, I could not give it.

In away I don't like the grading but I guess it helps others.

Hope this explain the "B" for you.

Lani
0
 
LVL 54

Expert Comment

by:b0lsc0tt
ID: 20330002
Lani,

Thanks for the explanation and reply.  It does make sense and I respect it.  No, there is no way to just selectively assign grades but I really appreciate the thought.

I noticed your grading history and see that you seem to be very fair (thanks on behalf of the experts :) ).  The recent advise you got sounds good.  I might just add that if you think the expert(s) would've provided the same solution you reached if they had time to respond or the info then it would be good to not penalize them (or the grade).  Many times the questioner just needs the nudge in the right direction and then finishes the solution on their own.  If that nudge is still detailed, specific and complete then it would fit an A.  If it is just a link or vague then a B would certainly be appropriate.  However I am not suggesting you change this or did anything wrong here since it was a little different (it seems). :)

There are no real "rules" to grading (EE does have a nice section in Help for a guide) so it is up to the Asker.  I was just curious (like many experts would be) and appreciate the explanation.  Thanks again for it and the fun question.  I'm glad I could help.

bol
0

Featured Post

IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

This article will give core knowledge of JavaScript and will head in to your first JavaScript program. I am Durvesh Naik and I am here to deal with this series of JavaScript. I will teach you JavaScript in part wise , as its quite boring to read big…
International Data Corporation (IDC) prognosticates that before the current the year gets over disbursing on IT framework products to be sent in cloud environs will be $37.1B.
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

758 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

19 Experts available now in Live!

Get 1:1 Help Now