473,659 Members | 2,886 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Checkbox form validation - how to make a user select 4 check boxes

14 New Member
Hello,
Checkbox form validation - how to make a user select 4 check boxes?
I have a question of a few checkboxes and how do I require a user to check 2 checkboxes (no more, no less)?

Here is my form:
<input type="checkbox" name="color" id="q" value="a" />A<BR />
<input type="checkbox" name="color" id="q2" value="b" />b<BR />
<input type="checkbox" name="color" id="q3" value="c" />c<BR />
<input type="checkbox" name="color" id="q4" value="d" />d<BR />

Thanks much.
May 11 '07 #1
12 2870
gits
5,390 Recognized Expert Moderator Expert
hi,

at the time you want to check you have different possibilities to achieve your goal :) you may loop through the elements and ask for check-attribs of them. if you find 2 checked ones you are done ... you may break the loop now and all is ok ...

you may also respond to the click-event at runtime ... when clicked/checked you might store the id of the checked element in an js-object or whatever you want to use for that ... then ... the right time you ask that object for stored data ... and if you find two or more stored ids ... you are done ...
May 11 '07 #2
pbmods
5,821 Recognized Expert Expert
Here's what I'm thinking...

[HTML]
<!-- Set to 'text' instead of 'hidden' so you can watch it make magic! -->
<input id="color0" name="color[]" type="text" value="" />
<input id="color1" name="color[]" type="text" value="" />

<p>
<input id="check0" type="checkbox" onclick="pushCh ex(this);" value="a" />a<br />
<input id="check1" type="checkbox" onclick="pushCh ex(this);" value="b" />b<br />
<input id="check2" type="checkbox" onclick="pushCh ex(this);" value="c" />c<br />
<input id="check3" type="checkbox" onclick="pushCh ex(this);" value="d" />d<br />
</p>

<script type="text/javascript">
var $chex = [null, null];
function pushChex($eleme nt) {

// If we check a box, add it to the array and shift off the first one.
if($element.che cked) {
$chex.push($ele ment);

$uncheck = $chex.shift();
if($uncheck)
$uncheck.checke d = false;

// If we uncheck a box, remove it from the array and push/unshift a null onto the other side.
} else {
if($chex[0] == $element)
$chex[0] = null;
else {
$chex.pop();
$chex.unshift(n ull);
}
}

// Update hidden inputs.
var $input;
for(var $i = 0; ($i < $chex.length) && ($input = document.getEle mentById('color ' + $i)); $i++)
$input.value = ($chex[$i]
? $chex[$i].value
: ''
);
}
</script>
[/HTML]

Methinks I had way too much fun with this one.

[EDIT: You're still going to have to check for > 0 checked when the User submits the form, and as much fun as this code looks, I'm pretty sure there's a more efficient way to do it ;)]
May 12 '07 #3
gits
5,390 Recognized Expert Moderator Expert
yep ... thats a fun thing ... and I tried it too ... using your example and changed it ... please excuse me ;)

[HTML]<p>
<input id="check0" type="checkbox" onclick="pushCh ex(this);" value="a" />a<br />
<input id="check1" type="checkbox" onclick="pushCh ex(this);" value="b" />b<br />
<input id="check2" type="checkbox" onclick="pushCh ex(this);" value="c" />c<br />
<input id="check3" type="checkbox" onclick="pushCh ex(this);" value="d" />d<br />
</p>

<p>
<div id="chex_conten t"></div>
</p>

<script type="text/javascript">
var $chex = {
length: 0,
eles : {}
};

function pushChex($eleme nt) {
if (typeof $chex.eles[$element.id] == 'undefined') {
if ($chex.length < 2) {
$chex.eles[$element.id] = $element;
$chex.length++;
} else {
$element.checke d = false;
alert('only 2 checked boxes allowed');
}
} else {
delete $chex.eles[$element.id];
$chex.length--;
}

// we write to the div to show what we have checked for now
// thats not needed for functionality only for demo

var $ct = document.getEle mentById('chex_ content');
$ct.innerHTML = '';

for (var i in $chex.eles) {
$ct.innerHTML += $chex.eles[i].id + '<br>';
}
}
</script>[/HTML]

so we only have to ask $chex for length to have the condition fullfilled that 2 have to be checked ...
May 12 '07 #4
tadisaus2
14 New Member
Thanks.
If a user check less than 2, it does not pop up errors.
I like to have a user to check at least 2 and NO more than 2.
Thanks.
May 14 '07 #5
gits
5,390 Recognized Expert Moderator Expert
at the time you want to check that ... probably on submitting the form, you have to ask $chex for length == 2 (assuming you use the code with the $chex-object) ... if this returns false, then you produce the error AND avoid submitting the form ... something like that:

Expand|Select|Wrap|Line Numbers
  1. // call that function on submit or at the point you want to check for
  2. // 2 checked boxes
  3.  
  4. function check_your_checkboxes() {
  5.     var val = $chex.length == 2;
  6.  
  7.     if (!val) {
  8.         alert('two checked boxes required');
  9.     }
  10.  
  11.     return val;
  12. }
  13.  
  14. // use the function to check within one that should submit the form ...
  15. // when returning false you don't perform the submit otherwise you do
  16.  
May 14 '07 #6
pbmods
5,821 Recognized Expert Expert
yep ... thats a fun thing ... and I tried it too ... using your example and changed it ... please excuse me ;)
You mean... you took some existing code and changed it to suit your purposes?

My goodness. What is this world coming to?

If a user check less than 2, it does not pop up errors.
I like to have a user to check at least 2 and NO more than 2.
That one you're gonna have to do manually.

Note in gits's post:

so we only have to ask $chex for length to have the condition fullfilled that 2 have to be checked ...
May 14 '07 #7
tadisaus2
14 New Member
Can I require a user to check at least 2 but No more than 2 boxes by using onBlur directly on the form. Fore example. when a user check ONLY 1 box and move to next field, then 1 error message pops up. I already have 1 function to check for empty checkboxes and don't know how to modify it to check at least two boxes.

var checkboxCk = false;
for (i = 0; i < document.frmnam e.chkFields.len gth; i++) {
if (document.frmna me.chkFields[i].checked)
checkboxCk = true; }
if (!checkboxCk) {
msgbox = msgbox + "\n Question #2, please check on this question";
}

Thanks.
May 14 '07 #8
gits
5,390 Recognized Expert Moderator Expert
You mean... you took some existing code and changed it to suit your purposes?

My goodness. What is this world coming to?
;) yep ... this world is bad and sad and ugly, nobody makes things hisself ... we reuse, refactor, steal ... shame on me :)

and now back to the problem: i assume the following now ... you've got your 4 checkboxes, probably as part of a survey, and before the user may switch to the next part of the survey you want to check, that he has exactly 2 checkboxes checked?

first: the function above checks already that you don't check more then 2 ... otherwise you get an alert ...

second: you are right to determine the point of getting the event that fires when the user wants to switch from your checkbox-section to an other ... but using onblur is sometimes annoying to the user ... until you give him the error without knowing whether he had checked the 2 boxes or not ... and he may think that this error is stupid, because he wanted to check 2 boxes ... perhaps you gave him a hint above the section, that he has to ... do you understand what i mean? ... its better to check after he's done, not during his actions ... so my advice would be: give every section a done-action (button or next-question-link or whatever) ... the user performs a click and you may check for whatever you want at this point ... and perhaps prepare your next question with the given results ... doing things implicit sometimes annoys the user until you need to know what he expects from your app ... a button/link/orwhatever to click is common ... and he knows what to do ...

if you don't want such an additional control i would recommend to rather check onfocus in the next section, than in your checkboxes ... assuming you use the above checkfunction that always responds to the click-event ...

hope i gave you an idea for achieving your goal?
May 14 '07 #9
tadisaus2
14 New Member
I agree with you not to use onBlur.
When I added this function on my existing JS function, it does not work.
function check_your_chec kboxes() {
var val = $chex.length == 2;
if (!val) {
alert('two checked boxes required');
}
return val;
}

Because I already have this to check for empty field check box.
var checkboxCk = false;
for (i = 0; i < document.frmnam e.chkFields.len gth; i++) {
if (document.frmna me.chkFields[i].checked)
checkboxCk = true; }
if (!checkboxCk) {
msgbox = msgbox + "\n Question #2, please check on this question";
}

Can you show me how to combine them together?

Thanks.
May 14 '07 #10

Sign in to post your reply or Sign up for a free account.

Similar topics

4
6162
by: Shufen | last post by:
Hi, I'm a newbie that just started to learn python, html and etc. I have some questions to ask and hope that someone can help me on. I'm trying to code a python script (with HTML) to get values from a html form that consists of about 10 checkbox and a textbox where user have to key in a value to perform a search. From python tutors, I learned that I have to use the following method:
5
3665
by: DotNetJunkies User | last post by:
1. i want to populate checkboxlist using javascript only at client side ....how can i do this..by populate word i mean that checkboxes should be checked or unchecked on some condition basis.... 2. after population there should be validation in checkboxlist..... that is if user clicks a button wihout checking any one of them(i.e. at least one shuld be checked) ... alerat message shouls come on the form....... these 2 steps should be...
34
3789
by: clinttoris | last post by:
Hello Experts, I have been told to post this in the Javascript forum as I want to do this client side just before my form gets submitted. Once the user clicks the submit button a javascript function needs to run and validate all the checkboxes on my form and make sure none of them are unchecked. I suck at Javascript and my problem is 2fold. I have the following code that constructs the checkbox response.write "<input type=checkbox...
6
4342
by: Daz | last post by:
Hi everyone. Firstly, I apologise if this i not what you would call a PHP problem. I get quite confused as to what lives in which realm, so if this shouldn't be posted here, please suggest where I should post it. I have created a form, which consists of a list of items, each with a checkbox. When a checkbox is checked or unchecked, the page should be refreshed. During the refresh, the data is validated and the MySQL database is...
29
3137
by: Amer Neely | last post by:
I've got a dynamically built form with checkboxes for each element ( a list of file names in a directory). I need to grab only those checkboxes that are checked, so I can then delete those files. Does each checkbox name have to be unique? I was hoping to just group them under one name, and select from that array. PHP is not my native language - I'm coming at this from Perl, so bear with me, things are a little different in that country.
11
4300
by: =?Utf-8?B?UGFyYWcgR2Fpa3dhZA==?= | last post by:
Hi All, I have a large recordset to be displayed on a ASP 3.0 page. I am using recordset paging for this. For the next and previous link i am passing href as <a href=<Page URl>?page=<%= iPageCurrent - 1 %for Previous. Now when i display the contents i also add a checkbox (for deletion) to each of the records. Now user should be able to select one or more checkboxes across pages and then should be allow to delete all selections together....
3
2908
by: Mahathi | last post by:
Hi I have a small problem in maintaining the state of a check box. Please do me a favour by telling me the procedure how to do that. My requirement is that "I have to map some roles with that of the users of the project. I have used checkboxes for selecting the roles that a particular user has. For example, an adminstrator has all roles in an organisation. Similarly an Employee has limited roles. Here let us take administrator...
2
4446
by: zufie | last post by:
I must combine the information from two forms/tabs on a main form. The idea is to insert two checkboxes on the main form. Then based on the checkbox checked would then automatically highlight those textboxes that need to be filled in by the end user. Any advice on how best to do this? Thanks!
1
4135
by: ahilar12 | last post by:
Hi all, I am new to php,my question is that in this following code i am retrieving many rows from the database which is working good.i want to delete a particular row(s) which is checked(checkbox) and this should be done when the deletecontact button is clicked and also should be deleted int the database also Somebody help me out on this code <html> <head> <script type="text/javascript"> function SetAllCheckBoxes(FormName,...
0
8427
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8332
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8746
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8525
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8627
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7356
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6179
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5649
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4335
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.