943,987 Members | Top Members by Rank

Ad:
You are currently viewing page 1 of this multi-page discussion thread
May 9th, 2009
0

Check if at least 1 Checkbox is selected? (form validation)

Expand Post »
I found something here, but I'm not good at javascript, and i don't know which part of the code is the right! I need only for Checkboxes!

JavaScript / DHTML / AJAX Syntax (Toggle Plain Text)
  1. http://www.codingforums.com/showthread.php?t=11165

I need something like:
onclick="check_if_at_least_one_is_selected()"

there is only one <form></form> and all checkboxes are same type...
Similar Threads
Reputation Points: 7
Solved Threads: 14
Junior Poster
smartness is offline Offline
103 posts
since Aug 2007
May 9th, 2009
0

Re: Check if at least 1 Checkbox is selected? (form validation)

Here you have it:
javascript Syntax (Toggle Plain Text)
  1. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
  2. "http://www.w3.org/TR/html4/loose.dtd">
  3. <html lang="en">
  4. <head>
  5. <meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7">
  6. <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
  7. <title>Test Page</title>
  8. <script type="text/javascript">
  9. <!--
  10. check = function( form ) {
  11. try {
  12. with( form ) { // Dual Mode
  13. if (!( chb0.checked ) && !( chb1.checked )) {
  14. alert( "You must atleast select 1 item in the field.");
  15. return false;
  16. } else {
  17. (( chb0.checked ) ? alert( "You've selected the following item:\n" + chb0.value ) : alert( "You've selected the following item:\n" + chb1.value )); }
  18. }
  19. } catch( e ) {
  20. if (!( form.chb0.checked ) && !( form.chb1.checked )) {
  21. alert( "You must atleast select 1 item in the field.");
  22. return false; } else {
  23. (( form.chb0.checked ) ? alert( "You've selected the following item:\n" + form.chb0.value ) : alert( "You've selected the following item:\n" + form.chb1.value ));
  24. }
  25. }
  26. }
  27. // -->
  28. </script>
  29. </head>
  30. <body>
  31. <form id="frm" action="#" onsubmit="return check( this );">
  32. <div>
  33. <label for="chb0">Check Field1: <input type="checkbox" id="chb0" name="chb0" value="CheckBox #1"></label><br>
  34. <label for="chb1">Check Field2: <input type="checkbox" id="chb1" name="chb1" value="CheckBoX #2"></label><br><br>
  35. <input type="submit" value="submit" id="sbm" name="sbm">
  36. </div>
  37. </form>
  38. </body>
  39. </html>
Featured Poster
Reputation Points: 114
Solved Threads: 138
Posting Shark
essential is offline Offline
973 posts
since Aug 2008
May 10th, 2009
0

Re: Check if at least 1 Checkbox is selected? (form validation)

Will this find cheboxes that do not Have chbX as a name/id?

Cuz my checkboxes are like this:
JavaScript / DHTML / AJAX Syntax (Toggle Plain Text)
  1. <input type="checkbox" name="792" value="Tekzilla Daily Tip" />
  2. <input type="checkbox" name="791" value="Daily Motion" />
  3. <input type="checkbox" name="789" value="Search" />

All checkboxes have id's like this! & I need to check if at least ONE of ALL checkboxes are checked... no matter what ID/NAME!
Reputation Points: 7
Solved Threads: 14
Junior Poster
smartness is offline Offline
103 posts
since Aug 2007
May 10th, 2009
0

Re: Check if at least 1 Checkbox is selected? (form validation)

It will search whatever ids you will provide. Just make sure that it's a valid one, and valid ids should start with alphabetic character's like: a791, chb791, etc.
Featured Poster
Reputation Points: 114
Solved Threads: 138
Posting Shark
essential is offline Offline
973 posts
since Aug 2008
May 15th, 2009
0

Re: Check if at least 1 Checkbox is selected? (form validation)

Doesn't work:
Firefox 3.0.10, error console:
Quote ...
Error: form.chb0 is undefined
Source File: http://localhost/test2/admin/searchterms.php
Line: 34
Reputation Points: 7
Solved Threads: 14
Junior Poster
smartness is offline Offline
103 posts
since Aug 2007
May 15th, 2009
0

Re: Check if at least 1 Checkbox is selected? (form validation)

you must provide your own ids for the element's inside your document, you don't have to use chb0 which is stated in posted code. Don't worry i'll provide another brief example for this issue.
Featured Poster
Reputation Points: 114
Solved Threads: 138
Posting Shark
essential is offline Offline
973 posts
since Aug 2008
May 15th, 2009
0

Re: Check if at least 1 Checkbox is selected? (form validation)

html Syntax (Toggle Plain Text)
  1. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
  2. "http://www.w3.org/TR/html4/loose.dtd">
  3. <html lang="en">
  4. <head>
  5. <meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7">
  6. <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
  7. <title>Test Page</title>
  8.  
  9. <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
  10. <script type="text/javascript">
  11. $(document).ready(function()
  12. {
  13. //Listens for form id "frm" to be submitted
  14. //When submitted checks if 1 or more checkboxes are checked.
  15. $('#frm').submit( function() {
  16.  
  17. //Look for ONLY checked inputs under this form
  18. var n = $('#frm :checked').length;
  19.  
  20. //If we have 1 or more show how many
  21. if( n > 0 ){ alert( n + ' are checked' ); }
  22. //Else show we have none that are checked
  23. else { alert( 'none are checekd' ); }
  24.  
  25. //Prevents form submission for demo
  26. return false;
  27. });
  28. });
  29. </script>
  30.  
  31. </head>
  32. <body>
  33. <form id="frm" action="#">
  34. <div>
  35. <label for="chb0">Check Field1:
  36. <input type="checkbox" id="chb0" name="chb0" value="CheckBox #1">
  37. </label><br>
  38. <label for="chb1">Check Field2:
  39. <input type="checkbox" id="chb1" name="chb1" value="CheckBoX #2">
  40. </label><br><br>
  41. <input type="submit" value="submit" id="sbm" name="sbm">
  42. </div>
  43. </form>
  44. <input type="checkbox" id="chb1" name="chb1" value="CheckBoX #2">
  45. </body>
  46. </html>

If you're going to be using javascript throughout your project I'd highly suggest looking at a library like jQuery. It will make you life much easier and the amount of power you gain as well as its cross browser compatibility is amazing.

This example illustrates checking if 1 or more checkboxes in your form a checked. the checkbox that is outside of the form will not contribute to the overall count. It also does NOT care what the inputs are named or their ids. It is looking for ANY input that is checked in your form which has an #id of frm. It also does not require any javascript to pollute your HTML.

Strip my comments out and you have about 5 lines of JS that are easy to understand.

http://docs.jquery.com/Main_Page
Last edited by mschroeder; May 15th, 2009 at 2:16 pm.
Sponsor
Reputation Points: 265
Solved Threads: 126
Practically a Master Poster
mschroeder is offline Offline
624 posts
since Jul 2008
May 15th, 2009
0

Re: Check if at least 1 Checkbox is selected? (form validation)

This will automatically check all checkboxes item's in your document. And doesn't need any editing.
javascript Syntax (Toggle Plain Text)
  1. <?xml version="1.0" encoding="utf-8"?>
  2. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
  3. "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
  4. <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
  5. <head>
  6. <meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7" />
  7. <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  8. <meta http-equiv="Content-Script-Type" content="text/javascript" />
  9. <title>Test Page</title>
  10. <script type="text/javascript">
  11. // <![CDATA[
  12. var check;
  13.  
  14. check = function( e ) {
  15. e = (( e ) ? e : window.event );
  16. t = (( e.target ) ? e.target : e.srcElement );
  17. if (( t.nodeName.toLowerCase() === "input" ) && ( t.type === "checkbox" && t.checked )) {
  18. alert( "You have checked the following item: " + t.value );
  19. val = (( t.checked ) ? "You've checked this item: <br />" + t.value : "" );
  20. (( document.getElementById ) ? document.getElementById("output").innerHTML = val : document.all.output = val );
  21. t.checked = false;
  22. }
  23. };
  24. document.onclick = check;
  25. // ]]>
  26. </script>
  27. </head>
  28. <body>
  29. <div id="main">
  30. <form id="myform" action="#" onsubmit="return false;">
  31. <div>
  32. <label for="c792">Tekzilla Daily Tip <input type="checkbox" id="c792" name="c792" value="Tekzilla Daily Tip" /></label><br />
  33.  
  34. <label for="c791">Daily Motion <input type="checkbox" id="c791" name="c791" value="Daily Motion" /></label><br />
  35. <label for="c789">Search <input type="checkbox" id="c789" name="c789" value="search" /></label>
  36. <!-- You can add more checkboxes here -->
  37. </div>
  38. </form>
  39. </div>
  40. <div id="output"></div>
  41. </body>
  42. </html>
Last edited by essential; May 15th, 2009 at 2:42 pm.
Featured Poster
Reputation Points: 114
Solved Threads: 138
Posting Shark
essential is offline Offline
973 posts
since Aug 2008
May 15th, 2009
0

Re: Check if at least 1 Checkbox is selected? (form validation)

The following code will also work on all major browsers EXCEPT Internet Explorer and IE-based browsers:

index.html
HTML Syntax (Toggle Plain Text)
  1. <html>
  2. <head>
  3. <script type="text/javascript" src="form_validate.js">
  4. // Script created 2009 KnifeySpooney
  5. // http://wurbo.com
  6. //
  7. // Completely free to use and modify
  8. </script>
  9. </head>
  10.  
  11. <body>
  12.  
  13. <form action="submit.php" method="get" onSubmit="validate(this); return false;">
  14. Test <input type="checkbox"/><br/>
  15. Test <input type="checkbox"/><br/>
  16. Test <input type="checkbox"/><br/>
  17. Test <input type="checkbox"/><br/>
  18. Test <input type="checkbox"/><br/>
  19. Test <input type="checkbox"/><br/>
  20. Test <input type="checkbox"/><br/>
  21. Test <input type="checkbox"/><br/>
  22. Test <input type="checkbox"/><br/>
  23. Test <input type="checkbox"/><br/>
  24. Test <input type="checkbox"/><br/>
  25. Test <input type="checkbox"/><br/>
  26. Test <input type="checkbox"/><br/>
  27. Test <input type="checkbox"/><br/>
  28. <br/><input type="submit" value="Submit"/>
  29. </form>
  30.  
  31. </body>
  32. </html>

form_validate.js
JavaScript Syntax (Toggle Plain Text)
  1. function validate(form) {
  2. var checkList = 0;
  3. var checks = document.evaluate(".//input[@type='checkbox']", form, null, 6, null);
  4.  
  5. for (var i=0; i<checks.snapshotLength; i++) {
  6. if (checks.snapshotItem(i).checked)
  7. checkList++;
  8. }
  9.  
  10. if (checkList > 0) {
  11. if (checkList == 1)
  12. alert("There was " + checkList + " checkbox marked.");
  13. else
  14. alert("There were " + checkList + " checkboxes marked.");
  15. }
  16. else
  17. alert("No checkboxes were marked.");
  18. }
Last edited by itsjareds; May 15th, 2009 at 7:04 pm.
Reputation Points: 39
Solved Threads: 13
Junior Poster
itsjareds is offline Offline
103 posts
since May 2009
May 15th, 2009
2

Re: Check if at least 1 Checkbox is selected? (form validation)

Poor smartness - advice overload I expect ......

..... but please let me join in.

This code:
  1. will validate as many independent groups of checkboxes as you like.
  2. will, on failure to validate :
    1. set a message in an HTML element of your choosing (by id), for each group independently, or
    2. give a javascript alert if no HTML element is provided for error messages
  3. is controlled from the HTML without needing to edit the javascript (except if you want different error messages, though that could be set in HTML too).
  4. works on IE and Firefox.
  5. is only 4 lines of code (if you put the worker function into a lib)!!!!
That said, I must give jquery a go some time.

JavaScript / DHTML / AJAX Syntax (Toggle Plain Text)
  1. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
  2. "http://www.w3.org/TR/html4/loose.dtd">
  3. <html>
  4. <head>
  5. <title>Test Page</title>
  6. <style type="text/css">
  7. html,body { font-size:10pt; }
  8. .checkBoxGroup { width:150px; margin:6px 0 0 0; padding:5px; border:1px solid #999999; }
  9. .checkBoxGroup h3 { margin:0; }
  10. p.errMsg { margin:0 0 9px 0; color:red; }
  11. </style>
  12.  
  13. <script type="text/javascript">
  14. check = function( form, chBoxGroups ) {
  15. result = true;
  16. if (chBoxGroups){ result = chBoxGroupValidator.scanGroups(chBoxGroups) && result; }
  17. //result = foo1() && result; //Do other checks here as necessary.
  18. //result = foo2() && result; //Do other checks here as necessary.
  19. //result = foo3() && result; //Do other checks here as necessary.
  20. return result;
  21. }
  22. var chBoxGroupValidator = function(){
  23. var setMsg = function(group, msg){
  24. var msgID = group.getAttribute('msgID');
  25. if(!msgID) { return false; }
  26. var msgEl = (document.getElementById) ? document.getElementById(msgID) : document.all[msgID];
  27. if(!msgEl) { return false; }
  28. msgEl.innerHTML = msg;
  29. return true;
  30. };
  31. var validateGroup = function(groupID){
  32. if (!groupID || typeof groupID != 'string') { return true; };//Invalid groupID - assume good.
  33. var qualifiers = false;
  34. var group = (document.getElementById) ? document.getElementById(groupID) : document.all[groupID];
  35. if(!group) { return true; }//group not found - assume good.
  36. var inputElements = group.getElementsByTagName('INPUT');
  37. for(var i=0; i<inputElements.length; i++) {
  38. if(inputElements[i].getAttribute('type') == 'checkbox') {
  39. qualifiers = true;
  40. if(inputElements[i].checked) {
  41. setMsg(group, '&nbsp;');
  42. return true;
  43. }
  44. }
  45. }
  46. if(qualifiers) {
  47. if( !setMsg(group, 'Select at least one item in this group') ) {
  48. var groupName = group.getAttribute('name');
  49. alert( ['You must select at least one item in the group : ', ((!groupName) ? '' : groupName)].join('') );
  50. }
  51. return false;
  52. }
  53. return true;
  54. };
  55. return {
  56. scanGroups : function(chBoxGroups){
  57. if (!chBoxGroups) { return true; }
  58. var result = true;
  59. if(typeof chBoxGroups == 'string') { chBoxGroups = [chBoxGroups]; }
  60. if(chBoxGroups.length) {
  61. for(var i=0; i<chBoxGroups.length; i++) { result = validateGroup(chBoxGroups[i]) && result; }
  62. }
  63. return result;
  64. }
  65. };
  66. }();
  67. </script>
  68. </head>
  69. <body>
  70. <form id="frm" action="#" onsubmit="return check( this, ['group_1', 'group_2'] );">
  71. <div id="group_1" name="Group 1" msgID="msg_1" class="checkBoxGroup">
  72. <h3>Group 1</h3>
  73. <label for="ch1_1">Check Field 1_1: <input type="checkbox" id="ch1_1" name="ch1_1" value="CheckBox 1_1"></label><br>
  74. <label for="ch1_2">Check Field 1_2: <input type="checkbox" id="ch1_2" name="ch1_2" value="CheckBoX 1_2"></label><br>
  75. </div>
  76. <p id="msg_1" class="errMsg">&nbsp;</p>
  77. <div id="group_2" name="Group 2" msgID="msg_2" class="checkBoxGroup">
  78. <h3>Group 2</h3>
  79. <label for="ch2_1">Check Field 2_1: <input type="checkbox" id="ch2_1" name="ch2_1" value="CheckBox 2_1"></label><br>
  80. <label for="ch2_2">Check Field 2_2: <input type="checkbox" id="ch2_2" name="ch2_2" value="CheckBoX 2_2"></label><br>
  81. <label for="ch2_3">Check Field 2_3: <input type="checkbox" id="ch2_3" name="ch2_3" value="CheckBoX 2_3"></label><br>
  82. </div>
  83. <p id="msg_2" class="errMsg">&nbsp;</p>
  84. <input type="submit" value="submit" id="sbm" name="sbm2">
  85. </form>
  86. </body>
  87. </html>
By the way, there's nothing wrong with the other guys' code. There are many ways to approach this.

Airshow
Sponsor
Reputation Points: 318
Solved Threads: 358
WiFi Lounge Lizard
Airshow is online now Online
2,527 posts
since Apr 2009

This thread is more than three months old

No one has posted to this discussion for at least three months. Please let old threads die and do not reply to them unless you feel you have something new and valuable to contribute that absolutely must be added to make the discussion complete. Otherwise, please start a new thread in this forum instead.
Message:
Previous Thread in JavaScript / DHTML / AJAX Forum Timeline: Form Field odd behavior IE
Next Thread in JavaScript / DHTML / AJAX Forum Timeline: Stretching DIV height





About Us | Contact Us | Advertise | Acceptable Use Policy
Forum Index | Build Custom RSS Feed


Follow us on Twitter


© 2011 DaniWeb® LLC