Solved

validate checkboxes and reqired a text field

Posted on 2009-07-14
8
331 Views
Last Modified: 2012-05-07
I have a page of checkboxes, each same name - I need to enable a textbox to be required, if ONE specific checkbox is checked.

I'm looking at this page, but haven't figured it out yet.  The sample is for one single check box, not a group.

http://docs.jquery.com/Plugins/Validation/Methods/required#dependency-expression

Below is my base code.. not sure exactly how to detect the correct check box or the syntax for it.

-- thanks!
<!-- jquery code-->
rules: {
group1: "required:
},
message:{
group1: "please choose from group 1",
group1Other: "Please type in your name"
}
 
<!-- html-->
 
<input type="checkbox" name="group1" value="a">
<input type="checkbox" name="group1" value="b">
<input type="checkbox" name="group1" value="c">
<input type="checkbox" name="group1" value="other">
<input type="text" name="group1Other"  value="">

Open in new window

0
Comment
Question by:PhotoMan2000
  • 4
  • 3
8 Comments
 
LVL 16

Expert Comment

by:anoyes
ID: 24856227
Basically what the dependency callback does is give you the ability to execute some function to determine if an item is required.  So, in your case, where you want to see if the other checkbox is checked, you'd have something like this:

<!-- jquery code-->
rules: {
group1: "required",
group1Other: {
 required: function(element) {
  return $("input[name='group1'][value='other']").is(':checked');
 }
}
},
message:{
group1: "please choose from group 1",
group1Other: "Please type in your name"
}
 
<!-- html-->
 
<input type="checkbox" name="group1" value="a">
<input type="checkbox" name="group1" value="b">
<input type="checkbox" name="group1" value="c">
<input type="checkbox" name="group1" value="other">
<input type="text" name="group1Other"  value="">

Open in new window

0
 
LVL 2

Expert Comment

by:onethreefour
ID: 24856253
One way you could do this is through some simple javascript embedded right in your form like this:

<input type="checkbox" name="group1" value="other" onClick="document.getElementById('group1Other').style.display = 'block';">
<input type="text" name="group1Other"  id='group1Other' value="" style='display:none;'>

This simply requires that you add an 'id' to the text box, and a 'style' setting it to NOT display...
Then you add the 'onClick' to your checkbox so that when it gets checked it makes the text box show up...    Of course this does not 'require' that the text box be filled out in order for them to post the form, additional error checking for that could be done in an onclick of the submit button or in the script that this form posts to, or several other ways...  

The above example is also so simple it also will not HIDE the text box if the check box is UNchecked... In order to accomplish that you could simply change your onclick in the checkbox to contain an if statement:
onClick="if (this.checked==true) {document.getElementById('group1Other').style.display = 'block';} else {document.getElementById('group1Other').style.display = 'none';}">

0
 

Author Comment

by:PhotoMan2000
ID: 24859973
@onetherrfour -- Thanks but I'm using JQuery.

@anoyes.

It works, sort of.  Here's the interaction the user sees.

24 check boxes. (All name='group1')
On the submit if none are checked, a message appears to check at least one box.
If they check any of the 24 the message disappears.
if the uncheck any of the 24 boxes, the message reappears.

If they happend to check the 24th, the message appears, BUT the error message for the text box ("group1Other" in snippet above) DOES NOT APPEAR.

What I WANT to see, is when they check the 24th box, the error also appears for that text box so that they are prompted to fill in the box.
0
How Do You Stack Up Against Your Peers?

With today’s modern enterprise so dependent on digital infrastructures, the impact of major incidents has increased dramatically. Grab the report now to gain insight into how your organization ranks against your peers and learn best-in-class strategies to resolve incidents.

 
LVL 16

Expert Comment

by:anoyes
ID: 24863241
can you post the full code for that page so i can run it locally and play around w/ it please.
0
 

Author Comment

by:PhotoMan2000
ID: 24863661
Ok,  here you go.
You'll need to link to your own .js file.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript" src="scripts/jquery-1.3.2.js" ></script>
<script type="text/javascript" src="scripts/jquery.validate.js" ></script>
<style type="text/css">
input.error {border:1px solid #990000}
label.error {background-color:#990000; color:#fff; padding:2px; float:left; clear:both;}
</style>
<title>Untitled Document</title>
</head>
 
<body>
<script type="text/javascript">
<!-- jquery code-->
$(document).ready(function()
	{
  	$("#form1").validate(
		{
		rules: {
			group1: "required",
			group1Other: {
				required: function(element) {
					return $("input[name='group1'][value='other']").is(':checked');
					}
				}
			},
		messages:{
			group1: "Pick at least one of the 24",
			group1Other: 'Please provide a name in the box'
			}			
	});	
  });
 </script>
<form id="form1" method="post">                          
<!-- html-->
 
<input type="checkbox" name="group1" value="1">
<input type="checkbox" name="group1" value="2">
<input type="checkbox" name="group1" value="3">
<input type="checkbox" name="group1" value="4">
<input type="checkbox" name="group1" value="5">
<input type="checkbox" name="group1" value="6">
<input type="checkbox" name="group1" value="7">
<input type="checkbox" name="group1" value="8">
<input type="checkbox" name="group1" value="9">
<input type="checkbox" name="group1" value="10">
<input type="checkbox" name="group1" value="11">
<input type="checkbox" name="group1" value="12">
<input type="checkbox" name="group1" value="13">
<input type="checkbox" name="group1" value="14">
<input type="checkbox" name="group1" value="15">
<input type="checkbox" name="group1" value="16">
<input type="checkbox" name="group1" value="17">
<input type="checkbox" name="group1" value="18">
<input type="checkbox" name="group1" value="19">
<input type="checkbox" name="group1" value="20">
<input type="checkbox" name="group1" value="22">
<input type="checkbox" name="group1" value="22">
<input type="checkbox" name="group1" value="23">
<input type="checkbox" name="group1" value="24">
<input type="checkbox" name="group1" value="other">
<input type="text" name="group1Other"  value="">
<input type="submit" name="button" id="button" value="Submit" />                          
</form>
 
</body>
</html>

Open in new window

0
 
LVL 16

Expert Comment

by:anoyes
ID: 24866290
Hmm it seems to be behaving OK for me...try clearing your cache perhaps?  What browser?

No boxes checked, hit submit, get the error 'please check one of the 24'. As soon as I check at least one, error disappears.

I check off a bunch of boxes, including 24, but do NOT fill in anything in the text box, hit submit, and get the error 'please provide a name in the box'.

I can check and uncheck boxes w/o generating errors (unless i check off the last box)

This is all the behavior you want, right?
0
 

Author Comment

by:PhotoMan2000
ID: 24869997
Yes, but the ONLY time the box's error should appear is IF the LAST box is checked AND the box is empty.
I noticed while playing, that the message sometimes didn't disappear when the last box is unchecked.

I also noticed that even if the last box is not checked any data previously entered remains. Can it be made to that an UNCHEKED state of the last box clears any information in the textbox?
0
 
LVL 16

Accepted Solution

by:
anoyes earned 500 total points
ID: 24873542
Let's see if this accomplishes it

<script type="text/javascript">
<!-- jquery code-->
var submitted = false;
$(document).ready(function() {
  $('form').submit(function() {
    submitted = true;
  });
  $("input[name='group1'][value='other']").click(function() {
    if (submitted == true) val.element($("input[name='group1Other']"));
    if (! $(this).is(':checked'))
      $("input[name='group1Other']").val('');
  });
  var val = $("#form1").validate({
    rules: {
      group1: "required",
      group1Other: {
        required: function(element) {
          return $("input[name='group1'][value='other']").is(':checked');
        }
      }
    },
    messages:{
      group1: "Pick at least one of the 24",
      group1Other: 'Please provide a name in the box'
    }            
  });     
});
 </script>

Open in new window

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!

Question has a verified solution.

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

This article demonstrates how to create a simple responsive confirmation dialog with Ok and Cancel buttons using HTML, CSS, jQuery and Promises
Boost your ability to deliver ambitious and competitive web apps by choosing the right JavaScript framework to best suit your project’s needs.
This tutorial walks through the best practices in adding a local business to Google Maps including how to properly search for duplicates, marker placement, and inputing business details. Login to your Google Account, then search for "Google Mapmaker…
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)

733 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