Link to home
Start Free TrialLog in
Avatar of cllocc
cllocc

asked on

Unable to make checkbox in our html form a required field

I have an html form that calls formail.pl and I've combined that with a js validitor script (inserted directly after the opening body tag) taken from here: http://www.dynamicdrive.com/dynamicindex16/requiredcheck.htm  to prompt the user to fill in the required fields.  I also have a checkbox on this form that for some reason isn't being validated by the js code I've included.  Here is the js code edited for my forms use:
<script language="JavaScript">
<!--

/***********************************************
* Required field(s) validation v1.10- By NavSurf
* Visit Nav Surf at http://navsurf.com
* Visit http://www.dynamicdrive.com/ for full source code
***********************************************/

function formCheck(formobj){
	// Enter name of mandatory fields
	var fieldRequired = Array("name","ss","dob","Address","city","State","zip","country","homephone","busphone","cellphone","emailadd","marstatus","parname","area","interest","comp1","comp2","comp3","from1","from2","from3","to1","to2","to3","title1","title2","title3","address1","address2","address3","agree");
	// Enter field description to appear in the dialog box
	var fieldDescription = Array("Name","Social Security #","Date of Birth","Address","City","State","Zip code","Country","Home Phone","Business Phone","Mobile Phone","Email Address","Marital Status","Names of all individuals who will have ownership","Area of interest","Business Interest","Company 1","Company 2","Company 3","from 1","from 2","from 3","to 1","to 2","to 3","Title 1","Title 2","Title 3","Address 1","Address 2","Address 3","Click on the box to agree to the Authorization and Release agreement");
	// dialog message
	var alertMsg = "Please complete the following fields:\n";
	
	var l_Msg = alertMsg.length;
	
	for (var i = 0; i < fieldRequired.length; i++){
		var obj = formobj.elements[fieldRequired[i]];
		if (obj){
			switch(obj.type){
			case "select-one":
				if (obj.selectedIndex == -1 || obj.options[obj.selectedIndex].text == ""){
					alertMsg += " - " + fieldDescription[i] + "\n";
				}
				break;
			case "select-multiple":
				if (obj.selectedIndex == -1){
					alertMsg += " - " + fieldDescription[i] + "\n";
				}
				break;
			case "text":
			case "textarea":
				if (obj.value == "" || obj.value == null){
					alertMsg += " - " + fieldDescription[i] + "\n";
				}
				break;
			default:
			}
			if (obj.type == undefined){
				var blnchecked = false;
				for (var j = 0; j < obj.length; j++){
					if (obj[j].checked){
						blnchecked = true;
					}
				}
				if (!blnchecked){
					alertMsg += " - " + fieldDescription[i] + "\n";
				}
			}
		}
	}

	if (alertMsg.length == l_Msg){
		return true;
	}else{
		alert(alertMsg);
		return false;
	}
}
// -->
</script>

Open in new window


Here is the checkbox portion of my html form:
<input type="checkbox" input id="agree" name="agree" value="agree" /> By checking this box, I confirm that I have read
                                       and agree to the Authorization and Release Agreement above.

Open in new window



I tried changing the checkbox to a radio button instead to see if that would work but I still had the same issue, the js validator would ignore it.

Any help would be greatly appreciated.
Avatar of Ray Paseur
Ray Paseur
Flag of United States of America image

Avatar of cllocc
cllocc

ASKER

I'm assuming I can just integrate this code at the end of the javascript code I currently have?  Or does it have to be placed in the beginning or any other specific place within the javascript code?

Thanks.
I think you would want to use the jQuery scripts consistently throughout the web page, so maybe it could replace the JS you have.  I'll try to give you an example.

Also, I think you might be able to test the length of the checkbox, since checkboxes are arrays.  Haven't tried that, but it seems possible.  A non-zero length in that element would indicate that it has been checked.
This seems to work correctly.
http://www.laprbass.com/RAY_temp_cllocc.php

<?php // RAY_temp_cllocc.php
error_reporting(E_ALL);

// IF THE FORM HAS BEEN POSTED
if (!empty($_POST))
{
    var_dump($_POST);
    die('Thanks for agreeing!');
}

?>

<!DOCTYPE html>
<html dir="ltr" lang="en-US">
<head>
<meta charset="utf-8" />
<title>Ajax Example Using jQuery with Two Variables</title>

<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript" src="http://jzaefferer.github.com/jquery-validation/jquery.validate.js"></script>

<script type="text/javascript">
jQuery.validator.setDefaults({
    debug: false,
    success: "valid"
});
</script>

<script>
$(document).ready(function(){
    $("#myform").validate({
        rules: {
            agree: "required"
        }
     });
});
</script>

<style>#agree { margin-left: .5em; float: left; }
  	#agree, label { float: left; font-family: Arial, Helvetica, sans-serif; font-size: small; }
	br { clear: both; }
	input { border: 1px solid black; margin-bottom: .5em;  }
	input.error { border: 1px solid red; }
	label.error {
		background: url('http://dev.jquery.com/view/trunk/plugins/validate/demo/images/unchecked.gif') no-repeat;
		padding-left: 16px;
		margin-left: .3em;
	}
	label.valid {
		background: url('http://dev.jquery.com/view/trunk/plugins/validate/demo/images/checked.gif') no-repeat;
		display: block;
		width: 16px;
		height: 16px;
	}
</style>
</head>
<body>

<form method="post" id="myform">
<label for="agree">Please agree to our policy</label>
<input type="checkbox" id="agree" title="Please agree to our policy!" name="agree" />
<br/>
<input type="submit" value="Validate!" />
</form>

</body>
</html>

Open in new window

HTH, ~Ray
Avatar of cllocc

ASKER

I was playing around with that some more and I tried adding additional (text) fields that are also required but once I did that, the validation didnt seem to work.  If I left only one field under rules then validation would work, but adding multiple fields under the first field in rules didnt seem to work?  Is that the proper method when trying to add multiple fields for the validation check or would I need to code in all our other required fields in a different way?
ASKER CERTIFIED SOLUTION
Avatar of Ray Paseur
Ray Paseur
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of cllocc

ASKER

I see. I will test that out and report back.
Avatar of cllocc

ASKER

Seem's like the same issue I was having with the previous js validation code I was working with.  The validator will recognize and text or numeric fields but for some reason, its not validating the checkbox.  I'm still able to submit the form without checking the box.  I double checked and saw that I did name and id the checkbox input as "agree".  Any idea as to why the jquery isnt checking for the checkbox?
Avatar of cllocc

ASKER

I saw this in the link you posted above, should I incorporate this into the jquery to account for the checkbox validation?

$("#myform").validate({
  rules: {
    details: {
      required: "#other:checked"
    }
  }, debug:true
});
$("#other").click(function() {
  $("#details").valid();
});

Open in new window

Avatar of cllocc

ASKER

unable to make any progress even when trying to implement the jquery script code above alongside the original code, which only seems to work for text/numeric based fields.
Avatar of cllocc

ASKER

OK, I just re-read the description for the jquery code snippet posted above and it seems its makes a field required after checking a box, which is not what I was looking for.  If anyone has any other ideas, any help would be greatly appreciated.
I am getting a sensible result from this code.  There are several examples in the jQuery document pages.  This is mostly a copy of one of them.

<?php // RAY_temp_cllocc.php
error_reporting(E_ALL);

// IF THE FORM HAS BEEN POSTED
if (!empty($_POST))
{
    var_dump($_POST);
    die('Thanks for agreeing!');
}

?>

<!DOCTYPE html>
<html dir="ltr" lang="en-US">
<head>
<meta charset="utf-8" />
<title>Ajax Example Using jQuery with Two Variables</title>

<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript" src="http://jzaefferer.github.com/jquery-validation/jquery.validate.js"></script>

<script type="text/javascript">
jQuery.validator.setDefaults({
    debug: false,
    success: "valid"
});
</script>

<script>
$(document).ready(function(){
    $("#myform").validate({
        rules: {
            agree: "required"
            , nom: "required"
        }
     });
});
</script>

<style>#agree { margin-left: .5em; float: left; }
  	#agree, label { float: left; font-family: Arial, Helvetica, sans-serif; font-size: small; }
	br { clear: both; }
	input { border: 1px solid black; margin-bottom: .5em;  }
	input.error { border: 1px solid red; }
	label.error {
		background: url('http://dev.jquery.com/view/trunk/plugins/validate/demo/images/unchecked.gif') no-repeat;
		padding-left: 16px;
		margin-left: .3em;
	}
	label.valid {
		background: url('http://dev.jquery.com/view/trunk/plugins/validate/demo/images/checked.gif') no-repeat;
		display: block;
		width: 16px;
		height: 16px;
	}
</style>
</head>
<body>

<form method="post" id="myform">
Name: <input id="nom" name="nom" title="Please enter your name" />
<label for="agree">Please agree to our policy</label>
<input type="checkbox" id="agree" title="Please agree to our policy!" name="agree" />
<br/>
<input type="submit" value="Validate!" />
</form>

</body>
</html>

Open in new window

Avatar of cllocc

ASKER

What is that PHP snippet before the doctype tag in the code you posted?  Should I assume that PHP code is already including in the formmail.pl we are using?  I will try copying and pasting your code as much as possible into the webpage I'm working on.
The PHP snippet is just there to prove to myself that the form actually got submitted with the correct information.  You would probably want to remove that and add the action= attribute to the <form> tag.
Avatar of cllocc

ASKER

well, when I copied the code you had above, I didnt include the php code in my selection.  I still was not able to get the code to validate the checkbox on my web page, though the form beautifully validated all text fields.  I finally came up with a work around, two validation methods. the jquery validation would be used for the text fields while I would use the built in validation method in the formmail.pl I was using for the checkbox.  The latter method causes a page redirect with a message to the user to go back and check the box but its better than nothing.  I spent most of my time today and some yesterday trying to figure out how to validate the checkbox but could no longer afford to waste time researching this issue.

Thanks for the jquery code, i  like it better than the javascript validation code i was using before, which caused a window to pop up informing the user which fields were required.  I much rather prefer jquery's method of no pop ups and instead jumping to the required field needing an input.
Avatar of cllocc

ASKER

Thanks that code helped me out a ton.
Thanks for the points, and best of luck with the project!