| | |
Check if at least 1 Checkbox is selected? (form validation)
Please support our JavaScript / DHTML / AJAX advertiser: PostgreSQL or MySQL? Compare and contrast the two most popular open source databases
![]() |
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!
I need something like:
onclick="check_if_at_least_one_is_selected()"
there is only one <form></form> and all checkboxes are same type...
JavaScript / DHTML / AJAX Syntax (Toggle Plain Text)
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...
Here you have it:
javascript Syntax (Toggle Plain Text)
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html lang="en"> <head> <meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>Test Page</title> <script type="text/javascript"> <!-- check = function( form ) { try { with( form ) { // Dual Mode if (!( chb0.checked ) && !( chb1.checked )) { alert( "You must atleast select 1 item in the field."); return false; } else { (( chb0.checked ) ? alert( "You've selected the following item:\n" + chb0.value ) : alert( "You've selected the following item:\n" + chb1.value )); } } } catch( e ) { if (!( form.chb0.checked ) && !( form.chb1.checked )) { alert( "You must atleast select 1 item in the field."); return false; } else { (( 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 )); } } } // --> </script> </head> <body> <form id="frm" action="#" onsubmit="return check( this );"> <div> <label for="chb0">Check Field1: <input type="checkbox" id="chb0" name="chb0" value="CheckBox #1"></label><br> <label for="chb1">Check Field2: <input type="checkbox" id="chb1" name="chb1" value="CheckBoX #2"></label><br><br> <input type="submit" value="submit" id="sbm" name="sbm"> </div> </form> </body> </html>
Will this find cheboxes that do not Have chbX as a name/id?
Cuz my checkboxes are like this:
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!
Cuz my checkboxes are like this:
JavaScript / DHTML / AJAX Syntax (Toggle Plain Text)
<input type="checkbox" name="792" value="Tekzilla Daily Tip" /> <input type="checkbox" name="791" value="Daily Motion" /> <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!
Doesn't work:
Firefox 3.0.10, error console:
Firefox 3.0.10, error console:
•
•
•
•
Error: form.chb0 is undefined
Source File: http://localhost/test2/admin/searchterms.php
Line: 34
•
•
Join Date: Jul 2008
Posts: 149
Reputation:
Solved Threads: 25
html Syntax (Toggle Plain Text)
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html lang="en"> <head> <meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>Test Page</title> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script> <script type="text/javascript"> $(document).ready(function() { //Listens for form id "frm" to be submitted //When submitted checks if 1 or more checkboxes are checked. $('#frm').submit( function() { //Look for ONLY checked inputs under this form var n = $('#frm :checked').length; //If we have 1 or more show how many if( n > 0 ){ alert( n + ' are checked' ); } //Else show we have none that are checked else { alert( 'none are checekd' ); } //Prevents form submission for demo return false; }); }); </script> </head> <body> <form id="frm" action="#"> <div> <label for="chb0">Check Field1: <input type="checkbox" id="chb0" name="chb0" value="CheckBox #1"> </label><br> <label for="chb1">Check Field2: <input type="checkbox" id="chb1" name="chb1" value="CheckBoX #2"> </label><br><br> <input type="submit" value="submit" id="sbm" name="sbm"> </div> </form> <input type="checkbox" id="chb1" name="chb1" value="CheckBoX #2"> </body> </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.
If you're question/problem is solved don't forget to mark the thread as Solved!
-- Code I post is usually but not always tested. If it is tested it will be against 5.2.12 or 5.3.1
-- Code I post is usually but not always tested. If it is tested it will be against 5.2.12 or 5.3.1
This will automatically check all checkboxes item's in your document. And doesn't need any editing.
javascript Syntax (Toggle Plain Text)
<?xml version="1.0" encoding="utf-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7" /> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta http-equiv="Content-Script-Type" content="text/javascript" /> <title>Test Page</title> <script type="text/javascript"> // <![CDATA[ var check; check = function( e ) { e = (( e ) ? e : window.event ); t = (( e.target ) ? e.target : e.srcElement ); if (( t.nodeName.toLowerCase() === "input" ) && ( t.type === "checkbox" && t.checked )) { alert( "You have checked the following item: " + t.value ); val = (( t.checked ) ? "You've checked this item: <br />" + t.value : "" ); (( document.getElementById ) ? document.getElementById("output").innerHTML = val : document.all.output = val ); t.checked = false; } }; document.onclick = check; // ]]> </script> </head> <body> <div id="main"> <form id="myform" action="#" onsubmit="return false;"> <div> <label for="c792">Tekzilla Daily Tip <input type="checkbox" id="c792" name="c792" value="Tekzilla Daily Tip" /></label><br /> <label for="c791">Daily Motion <input type="checkbox" id="c791" name="c791" value="Daily Motion" /></label><br /> <label for="c789">Search <input type="checkbox" id="c789" name="c789" value="search" /></label> <!-- You can add more checkboxes here --> </div> </form> </div> <div id="output"></div> </body> </html>
Last edited by essential; May 15th, 2009 at 2:42 pm.
The following code will also work on all major browsers EXCEPT Internet Explorer and IE-based browsers:
index.html HTML Syntax (Toggle Plain Text)
<html> <head> <script type="text/javascript" src="form_validate.js"> // Script created 2009 KnifeySpooney // http://wurbo.com // // Completely free to use and modify </script> </head> <body> <form action="submit.php" method="get" onSubmit="validate(this); return false;"> Test <input type="checkbox"/><br/> Test <input type="checkbox"/><br/> Test <input type="checkbox"/><br/> Test <input type="checkbox"/><br/> Test <input type="checkbox"/><br/> Test <input type="checkbox"/><br/> Test <input type="checkbox"/><br/> Test <input type="checkbox"/><br/> Test <input type="checkbox"/><br/> Test <input type="checkbox"/><br/> Test <input type="checkbox"/><br/> Test <input type="checkbox"/><br/> Test <input type="checkbox"/><br/> Test <input type="checkbox"/><br/> <br/><input type="submit" value="Submit"/> </form> </body> </html>
form_validate.js JavaScript Syntax (Toggle Plain Text)
function validate(form) { var checkList = 0; var checks = document.evaluate(".//input[@type='checkbox']", form, null, 6, null); for (var i=0; i<checks.snapshotLength; i++) { if (checks.snapshotItem(i).checked) checkList++; } if (checkList > 0) { if (checkList == 1) alert("There was " + checkList + " checkbox marked."); else alert("There were " + checkList + " checkboxes marked."); } else alert("No checkboxes were marked."); }
Last edited by itsjareds; May 15th, 2009 at 7:04 pm.
Poor smartness - advice overload I expect ......
..... but please let me join in.
This code:
By the way, there's nothing wrong with the other guys' code. There are many ways to approach this.
Airshow
..... but please let me join in.
This code:
- will validate as many independent groups of checkboxes as you like.
- will, on failure to validate :
- set a message in an HTML element of your choosing (by id), for each group independently, or
- give a javascript alert if no HTML element is provided for error messages
- 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).
- works on IE and Firefox.
- is only 4 lines of code (if you put the worker function into a lib)!!!!
JavaScript / DHTML / AJAX Syntax (Toggle Plain Text)
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <title>Test Page</title> <style type="text/css"> html,body { font-size:10pt; } .checkBoxGroup { width:150px; margin:6px 0 0 0; padding:5px; border:1px solid #999999; } .checkBoxGroup h3 { margin:0; } p.errMsg { margin:0 0 9px 0; color:red; } </style> <script type="text/javascript"> check = function( form, chBoxGroups ) { result = true; if (chBoxGroups){ result = chBoxGroupValidator.scanGroups(chBoxGroups) && result; } //result = foo1() && result; //Do other checks here as necessary. //result = foo2() && result; //Do other checks here as necessary. //result = foo3() && result; //Do other checks here as necessary. return result; } var chBoxGroupValidator = function(){ var setMsg = function(group, msg){ var msgID = group.getAttribute('msgID'); if(!msgID) { return false; } var msgEl = (document.getElementById) ? document.getElementById(msgID) : document.all[msgID]; if(!msgEl) { return false; } msgEl.innerHTML = msg; return true; }; var validateGroup = function(groupID){ if (!groupID || typeof groupID != 'string') { return true; };//Invalid groupID - assume good. var qualifiers = false; var group = (document.getElementById) ? document.getElementById(groupID) : document.all[groupID]; if(!group) { return true; }//group not found - assume good. var inputElements = group.getElementsByTagName('INPUT'); for(var i=0; i<inputElements.length; i++) { if(inputElements[i].getAttribute('type') == 'checkbox') { qualifiers = true; if(inputElements[i].checked) { setMsg(group, ' '); return true; } } } if(qualifiers) { if( !setMsg(group, 'Select at least one item in this group') ) { var groupName = group.getAttribute('name'); alert( ['You must select at least one item in the group : ', ((!groupName) ? '' : groupName)].join('') ); } return false; } return true; }; return { scanGroups : function(chBoxGroups){ if (!chBoxGroups) { return true; } var result = true; if(typeof chBoxGroups == 'string') { chBoxGroups = [chBoxGroups]; } if(chBoxGroups.length) { for(var i=0; i<chBoxGroups.length; i++) { result = validateGroup(chBoxGroups[i]) && result; } } return result; } }; }(); </script> </head> <body> <form id="frm" action="#" onsubmit="return check( this, ['group_1', 'group_2'] );"> <div id="group_1" name="Group 1" msgID="msg_1" class="checkBoxGroup"> <h3>Group 1</h3> <label for="ch1_1">Check Field 1_1: <input type="checkbox" id="ch1_1" name="ch1_1" value="CheckBox 1_1"></label><br> <label for="ch1_2">Check Field 1_2: <input type="checkbox" id="ch1_2" name="ch1_2" value="CheckBoX 1_2"></label><br> </div> <p id="msg_1" class="errMsg"> </p> <div id="group_2" name="Group 2" msgID="msg_2" class="checkBoxGroup"> <h3>Group 2</h3> <label for="ch2_1">Check Field 2_1: <input type="checkbox" id="ch2_1" name="ch2_1" value="CheckBox 2_1"></label><br> <label for="ch2_2">Check Field 2_2: <input type="checkbox" id="ch2_2" name="ch2_2" value="CheckBoX 2_2"></label><br> <label for="ch2_3">Check Field 2_3: <input type="checkbox" id="ch2_3" name="ch2_3" value="CheckBoX 2_3"></label><br> </div> <p id="msg_2" class="errMsg"> </p> <input type="submit" value="submit" id="sbm" name="sbm2"> </form> </body> </html>
Airshow
![]() |
Similar Threads
- Javascript checkbox validation (JavaScript / DHTML / AJAX)
- Form Validation-Alert box (JavaScript / DHTML / AJAX)
- coldfusion form validation question (ColdFusion)
- Create Alpha numeric code Verification????? (PHP)
- Validation of checkbox (PHP)
- need help requiring at least one checkbox from group to be selected (JavaScript / DHTML / AJAX)
- Looping through arrays (PHP)
- Processing array values (PHP)
Other Threads in the JavaScript / DHTML / AJAX Forum
- Previous Thread: AJAX / XMLHttpRequest working in all browsers except firefox. Please Help
- Next Thread: Javascript help with random letter thingy
Views: 3055 | Replies: 9
| Thread Tools | Search this Thread |
Tag cloud for JavaScript / DHTML / AJAX
ajax ajaxcode ajaxhelp animate api automatically beta boarder box bug button calendar card checkbox child class column cookies createrange() css cursor disablefirebug dom download dropdown editor element engine error events explorer ext file firehose flash form forms google gwt html htmlform ie8 iframe image() images internet java javascript jawascriptruntimeerror jquery jsf jsfile jump margin math matrixcaptcha microsoft mimic mp3 mysql object offline onmouseoutdivproblem onreadystatechange parent passing pdf php player post problem progressbar rated rating regex runtime scroll search select session shopping size sql star stars stretch text textarea twitter validation w3c web website window windowofwords windowsxp wysiwyg xml xspf \n





