?
Solved

Unable to make checkbox in our html form a required field

Posted on 2012-09-14
17
Medium Priority
?
710 Views
Last Modified: 2012-09-14
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.
0
Comment
Question by:cllocc
  • 10
  • 7
17 Comments
 
LVL 111

Expert Comment

by:Ray Paseur
ID: 38399346
0
 

Author Comment

by:cllocc
ID: 38399375
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.
0
 
LVL 111

Expert Comment

by:Ray Paseur
ID: 38399414
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.
0
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!

 
LVL 111

Expert Comment

by:Ray Paseur
ID: 38399464
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
0
 

Author Comment

by:cllocc
ID: 38399503
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?
0
 
LVL 111

Accepted Solution

by:
Ray Paseur earned 2000 total points
ID: 38399539
I think you can do it like this.  The look and feel is kind of clunky in the example, but at least it shows how to require multiple fields.

<!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

0
 

Author Comment

by:cllocc
ID: 38399555
I see. I will test that out and report back.
0
 

Author Comment

by:cllocc
ID: 38399977
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?
0
 

Author Comment

by:cllocc
ID: 38400025
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

0
 

Author Comment

by:cllocc
ID: 38400077
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.
0
 

Author Comment

by:cllocc
ID: 38400261
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.
0
 
LVL 111

Expert Comment

by:Ray Paseur
ID: 38400345
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

0
 

Author Comment

by:cllocc
ID: 38400370
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.
0
 
LVL 111

Expert Comment

by:Ray Paseur
ID: 38400427
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.
0
 

Author Comment

by:cllocc
ID: 38400532
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.
0
 

Author Closing Comment

by:cllocc
ID: 38400533
Thanks that code helped me out a ton.
0
 
LVL 111

Expert Comment

by:Ray Paseur
ID: 38400572
Thanks for the points, and best of luck with the project!
0

Featured Post

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Without even knowing it, most of us are using web applications on a daily basis.  In fact, Gmail and Yahoo email, Twitter, Facebook, and eBay are used by most of us daily—and they are web applications. We generally confuse these web applications to…
The first step to building an amazing About page is to figure out what you want the page to say about your company. You then must grab the attention of the reader, boast a bit, tell a story and let others brag about you. With a little bit of thought…
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.
Suggested Courses
Course of the Month16 days, 1 hour left to enroll

850 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