Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Checkbox validation with array as name 1

Status
Not open for further replies.

MockY

Programmer
Jul 7, 2006
94
I am creating a form that currently work just fine but I do want to add some validation to reinforce required fields. I am using a javascript that works just like I want it too, but only for fields. Throughout the form, I am using a fair amount of check boxes, and in this thread I am cutting the form down to bare minimum so it is easier for me to show what I am trying to accomplish, but it is fully functional.

The problem that I am having is that I use arrays as names for the checkboxes. This is because I use PHP loops for display of the content of the boxes and I can't therefore address the checkboxes individually. First and foremost, below is the form (just a snippet but in working condition)

Code:
<form method="post" name="form" action="formmail.php" >
<div>Information</div>

<table>
  <tr>
    <td>Name:</td>
    <td><input name="holdername" type="text" size="26" /></td>
    <td>Policy#:</td>
    <td><input name="holderpolicy" type="text" size="26" /></td>
  </tr>
  <tr>
    <td>Phone:</td>
    <td><input name="holderphone" type="text" size="26" /></td>
    <td>Email:</td>
    <td><input name="holderemail" type="text" size="26" /></td>
  </tr>
</table>

<table>
  <tr>
    <td><input type="checkbox" name="requirements[]" value="Proof" /></td>
    <td>Proof</td>
  </tr>
  <tr>
    <td><input type="checkbox" name="requirements[]" value="Additional" /></td>
    <td>Additional</td>
  </tr>
</table>

<table>
  <tr>
    <td colspan="6">What is the job type?</td>
  </tr>
  <tr>
    <td><input type="checkbox" name="jobtype[]" value="New Stuff" /></td>
    <td>New Stuff</td>
    <td><input type="checkbox" name="jobtype[]" value="Remodel" /></td>
    <td>Remodel</td>
    <td><input type="checkbox" name="jobtype[]" value="Old Stuff" /></td>
    <td>Old Stuff</td>
  </tr>
</table>
  
<input type="submit" value="Send" name="submit" id="formbutton" onclick="return verify()" /> 
     
</form>

And here below is the javascript that I am using to validate the required fields:

Code:
<Script language="JavaScript">

function verify() {
var themessage = "You are required to complete the following fields: \n\n";
if (document.form.holdername.value=="") {
themessage = themessage + " Holder Name\n";
}
if (document.form.holderphone.value=="") {
themessage = themessage + "Holder Phone Number\n";
}
if (document.form.holderpolicy.value=="") {
themessage = themessage + "Holder Policy #\n";
}

//alert if fields are empty and cancel form submit
if (themessage == "You are required to complete the following fields: \n\n") {
document.form.submit();
}
else {
alert(themessage);
return false;
   }
}
</script>

This form requires the user to fill in information in 3 of the fields. So far so good. Using this javascript and the form together, it works just fine. However, now comes my issue.

Depending on what box you check (Proof or Additional), further requirements are needed.
In this case, If you check the Additional checkbox, one or more of the job type boxes are required to be checked as well. But If you check the Proof box, no further validation is required at all and the user can send the form.

How do I go about to do this?

For the one who wonder, an example PHP loop that I use in the target file looks like this:

Code:
if(is_array($_POST['requirements']))
	 foreach($_POST['requirements'] as $requirementschecked)
  	 {
	 $requirementsprint .= "$requirementschecked";
	 }
 
Here is one way to do this (using the form data you posted):
Code:
<script type="text/javascript">
...
function validateCheckboxes() {
  var themessage = "";
  var frm = document.forms['form'];
  var reqcheckboxes = frm.getElementsByName('requirements[]');
  if (!reqcheckboxes[0].checked) {
    // proof checkbox was not checked
    if (reqcheckboxes[1].checked) {
      // additional checkbox was checked
      var jobtypecheckboxes = frm.getElementsByName('jobtype[]');
      if (!jobtypecheckboxes[0].checked && !jobtypecheckboxes[1].checked && !jobtypecheckboxes[2].checked) {
        // no jobtype checkboxes were checked
        themessage += "You need to choose at least one Jobtype\n";
      }
    } else {
      // neither the proof or requirements checkboxes were checked
      themessage += "Either the Proof or Additional checkboxes must be checked\n";
    }
  }
  return themessage;
}
...
</script>
You would then call the validateCheckboxes() function and append it's result to themessage variable like this:
Code:
...
themessage += validateCheckboxes();
...
Another way would be to put classnames on the checkboxes and then you could iterate over a collection of all the inputs and test the classnames. It all depends on how obtrusive you want to be I guess [smile]

Shout if you need a hand,
Jeff

[tt]Jeff's Blog [!]@[/!] CodeRambler
[/tt]

Make sure your web page and css validates properly against the doctype you have chosen - before you attempt to debug a problem!

FAQ216-6094
 
Thank you so much for your response. I do have issues understanding how I would call the validateCheckboxes() function and how I would go about to use both functions at the same time.
Could you please elaborate on that?
 
Sure. Inside the verify() function, place the following line before the part where you do the submit/alert.
Code:
themessage += validateCheckboxes();
Cheers,
Jeff

[tt]Jeff's Blog [!]@[/!] CodeRambler
[/tt]

Make sure your web page and css validates properly against the doctype you have chosen - before you attempt to debug a problem!

FAQ216-6094
 
It seems like it doesn't matter where I put validateCheckboxes(), the verify() function stops to work if I include it. I hope you don't get frustrated with me now, but I can't see why it shouldn't work.
 
The problem I think is that themessage must have the exact string as when the variable was initiated. Including anything else will make it untrue and the form will be sent.
 
Ah. Yes. Well... I guess that's because my coding patterns are different to yours [smile]. Personally, when trying to build up an alert string (like that) I tend to start with a blank string and append to the string the errors (as they occur). I then test that the string is still empty (if it is I submit, if not I prepend the initial string text you use and alert the message then).

An alternative would be:
Code:
var tempmessage = validateCheckboxes();
if (tempmessage != '') {
  themessage += tempmessage;
}
That should get you going!

Cheers,
Jeff

[tt]Jeff's Blog [!]@[/!] CodeRambler
[/tt]

Make sure your web page and css validates properly against the doctype you have chosen - before you attempt to debug a problem!

FAQ216-6094
 
MockY,

Don't forget about the "Thank <postername> for this valuable post" link at the bottom of each post. Looking through your stats, I can see you've been a member for almost 2 years, have asked plenty of questions, but have never used it yet.

Dan



Coedit Limited - Delivering standards compliant, accessible web solutions

[tt]Dan's Page [blue]@[/blue] Code Couch
[/tt]
 
Ohh my, I am so sorry, I was not aware of that feature and I'll make sure to use it from now on. I do remember looking for a "Thread Solved" feature in the past but was not able to find it, and surprisingly this Thank You feature was missed then as well.
Thanks for pointing that out.

BabyJeffy,
I will make darn sure that I'll do my best to get this working. I am of a PHP background and JavaScript is fairly new to be, so sorry in advance if I make you pull your hair of frustration.
 
I made some minor changes in the verify() function so that I can read it a bit better but any changing in the verify() function breaks it, and the message is sent through regardless. To me, the code looks like it should work just fine but for some reason it doesn't.

So without any calling for the validateCheckboxes() (though it's present), here is the code right now.

Code:
<script type="text/javascript">

function validateCheckboxes() {
  var themessage = "";
  var frm = document.forms['form'];
  var reqcheckboxes = frm.getElementsByName('requirements[]');
  if (!reqcheckboxes[0].checked) {
    // proof checkbox was not checked
    if (reqcheckboxes[1].checked) {
      // additional checkbox was checked
      var jobtypecheckboxes = frm.getElementsByName('jobtype[]');
      if (!jobtypecheckboxes[0].checked && !jobtypecheckboxes[1].checked && !jobtypecheckboxes[2].checked) {
        // no jobtype checkboxes were checked
        themessage += "You need to choose at least one Jobtype\n";
      }
    } else {
      // neither the proof or requirements checkboxes were checked
      themessage += "Either the Proof or Additional checkboxes must be checked\n";
    }
  }
  return themessage;
}

function verify() {
var themessage = "";

//alert if fields are empty and cancel form submit
if (document.form.holdername.value=="") {
themessage = themessage + " Holder Name\n";
}
if (document.form.holderphone.value=="") {
themessage = themessage + "Holder Phone Number\n";
}
if (document.form.holderpolicy.value=="") {
themessage = themessage + "Holder Policy #\n";
}

// If it is ampty, no error is presumed and the form is sent
if (themessage == "") {
document.form.submit();
}
else {
alert("You need to complete the following fields:\n\n" + themessage);
return false;
   }
}

</script>
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top