• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 976
  • Last Modified:

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

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
lanivanvuuren
Asked:
lanivanvuuren
  • 5
  • 4
  • 2
3 Solutions
 
anoyesCommented:
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
 
b0lsc0ttCommented:
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
 
lanivanvuurenAuthor Commented:
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
Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

 
lanivanvuurenAuthor Commented:
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
 
anoyesCommented:
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
 
lanivanvuurenAuthor Commented:
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
 
lanivanvuurenAuthor Commented:
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
 
b0lsc0ttCommented:
>> 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
 
b0lsc0ttCommented:
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
 
lanivanvuurenAuthor Commented:
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
 
b0lsc0ttCommented:
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

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

  • 5
  • 4
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now