Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations dencom on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

javascript newbie - question about validating checkbox? 5

Status
Not open for further replies.

sophielois

Technical User
Sep 8, 2005
66
GB
Hello,

i have very little knowledge of javascript but need a little for a form im using. can anyone help??

I need to limit people from only being able to check 2 check boxes.

here is the code for the form im using
Code:
<form action="add3.php" method="post" onsubmit="return check(this)">
  <table width="610" border="0" cellspacing="0" cellpadding="0">
    <tr> 
      <td width="27" height="27"> <input type="checkbox" name="hsc25" value="yes"></td>
      <td width="193">HSC25</td>
      <td width="29"><input type="checkbox" name="hsc221" value="yes"></td>
      <td width="180">HSC221</td>
      <td width="26"><input type="checkbox" name="hsc223" value="yes"></td>
      <td width="155">HSC223</td>
    </tr>
    <tr> 
      <td height="34"> 
        <input type="checkbox" name="hsc210" value="yes"></td>
      <td>HSC210</td>
      <td><input type="checkbox" name="hsc218" value="yes"></td>
      <td>HSC218</td>
      <td><input type="checkbox" name="hsc21314" value="yes"></td>
      <td>HSC213-14</td>
    </tr>
    <tr> 
      <td><input type="checkbox" name="hsc226" value="yes"></td>
      <td>HSC226</td>
      <td>&nbsp;</td>
      <td>&nbsp;</td>
      <td>&nbsp;</td>
      <td>&nbsp;</td>
    </tr>
  </table>
  <input type="hidden" name="userid" value="<?= $userid ?>">
  <input type="submit" name="add" value="Proceed">
</form>

Thank you for any advice that anybody can give me.

Sophx
 
Show us the javascript you have so far.


~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
O Time, Strength, Cash, and Patience! [infinity]
 
By the way, consider making the NAME attribute of all the checkboxes the same and making their ID's unique.

Dave


~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
O Time, Strength, Cash, and Patience! [infinity]
 
hi LFI,

At the moment i dont have any javascript as i have never had to validate check boxes before. My javascript knowledge goes as far as something like this

Code:
  if (theForm.firstname.value == "")
  {
    alert("Please enter the first name.");
    theForm.firstname.focus();
    return (false);
  }

also could you explain why this
"consider making the NAME attribute of all the checkboxes the same and making their ID's unique" would be "better practice" as before changing i would like to learn why im doing it.

Thanks
Soph x
 
If the checkboxes are all of the same name, you can handle them as an array.

Code:
var cbs = document.forms[0].elements[cbName];
var count = 0;
for(var i=0; i<cbs.length; i++)
{
 if(cbs[i].checked)
  count++;
}
alert('You have checked ' + count + ' checkboxes');

Does this make sense?

Dave


~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
O Time, Strength, Cash, and Patience! [infinity]
 
LFI said:
By the way, consider making the NAME attribute of all the checkboxes the same

The only time the name attribute should be the same is for multiple inputs is when they form a radio group:
Code:
  <input type="radio" name="foo" id="foo1" />
  <input type="radio" name="foo" id="foo2" />
  <input type="radio" name="foo" id="foo3" />
  <input type="radio" name="foo" id="foo4" />
You should add unique IDs in order to support label tags. Good practice is to make the ID identical to the name, except for the case of radio groups, where the ID must be unique, but the name of each input in the group must be identical:
Code:
  <label [COLOR=red]for="username"[/color]>Username:</label>
  <input [COLOR=red]id="username"[/color] name="username" />
  <br />
  <label [COLOR=red]for="email"[/color]>Email:</label>
  <input [COLOR=red]id="email"[/color] name="email" />
  <br />

  <p>Gender:</p>
  <label [COLOR=red]for="gender_male"[/color]>Male</label>
  <input [COLOR=red]id="gender_male"[/color] name="gender" value="male" />
  <br />
  <label [COLOR=red]for="gender_female"[/color]>Female</label>
  <input [COLOR=red]id="gender_female"[/color] name="gender" value="female" />
  <br />

---
Marcus
better questions get better answers - faq581-3339
accessible web design - zioncore.com
 
manarth said:
The only time the name attribute should be the same is for multiple inputs is when they form a radio group

Why not when they form a checkbox group, as in this case?

--Dave


~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
O Time, Strength, Cash, and Patience! [infinity]
 
Fair point Dave, you can assign a group of checkboxes the same name (as long as they have unique values). I'm so used to the convention of having matching names & IDs that I forgot it wasn't set in stone!

I've never really thought of checkbox 'groups' before; radio groups are groups because you can choose only one of them, whilst I've always viewed each checkbox seperately as an individual true|false.

---
Marcus
better questions get better answers - faq581-3339
accessible web design - zioncore.com
 
I'm certain I can think of a situation where it is preferable to name the checkboxes uniquely. What I like about naming them the same in this case, however, is that, since there is a limit on the number that may be checked, the javascript can handle these boxes without accidentally including other checkboxes which may be on the page, but are there for some other reason.

Dave


~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
O Time, Strength, Cash, and Patience! [infinity]
 
Code:
<script>
    function checkAll(objName)
      {
        var obj = document.getElementsByName(objName);
        listi = obj.length;
        var check_track = 0;
         for(var i = 0; i <= listi; ++i)
          {
       		if(obj[i].checked == true)
        		{
        		    ++check_track;
        			if(check_track == 3)
        				{
        				alert("you have selected to many choices");
        				obj[i].checked == false;
        				}
        		}
          }
      }
</script>



<form action="" name="cbs" method="post" onsubmit="">
  <table width="610" border="0" cellspacing="0" cellpadding="0">
    <tr>
      <td width="27" height="27"> <input type="checkbox" name="hsc" id="hsc1" value="yes"></td>
      <td width="193">HSC25</td>
      <td width="29"><input type="checkbox" name="hsc" id="hsc2" value="yes"></td>
      <td width="180">HSC221</td>
      <td width="26"><input type="checkbox" name="hsc" id="hsc3" value="yes"></td>
      <td width="155">HSC223</td>
    </tr>
    <tr>
      <td height="34">
      <input type="checkbox" name="hsc" id="hsc4" value="yes"></td>
      <td>HSC210</td>
      <td><input type="checkbox" name="hsc" id="hsc5" value="yes"></td>
      <td>HSC218</td>
      <td><input type="checkbox" name="hsc" id="hsc6" value="yes"></td>
      <td>HSC213-14</td>
      <td><input type="checkbox" name="hsc" id="hsc7" value="yes"></td>
      <td>HSC226</td>
      <td>&nbsp;</td>
      <td>&nbsp;</td>
      <td>&nbsp;</td>
      <td>&nbsp;</td>
    </tr>
  </table>
   <button onClick="return checkAll('hsc')">check</button>
</form>
Sample working code, tested on firefox. Will alert when if more than boxes have been checked. Hope this helps.
 
OK, I concede ;-) It does have a certain appeal to it!


sophielois, something like this will prevent more than 2 checkboxes being checked.
Code:
  <input type="checkbox" name="hsc" value="225" onchange="checkTotal(this);" />
  <input type="checkbox" name="hsc" value="221" onchange="checkTotal(this);" />
  <input type="checkbox" name="hsc" value="223" onchange="checkTotal(this);" />

Code:
[COLOR=green]/* variable to track how many checkboxes are checked */[/color]
var hscTotalChecked=0;

[COLOR=green]/* hsc holds an object collection (similar to an array) of the checkboxes with the matching name */[/color]
var hsc = document.getElementsByName('hsc');


function checkTotal(checkbox) {
  if (checkbox.checked==true) hscTotalChecked++; else hscTotalChecked--;
  for (i=0; i<hsc.length; i++) {
    if (hscTotalChecked==2 && hsc[i].checked==false) {
      hsc.disabled = true;
    } else {
      hsc.disabled = false;
    }
  }
}

There are more efficient ways to write the script, but you should I hope be able to understand how this works and suit it to your app.

---
Marcus
better questions get better answers - faq581-3339
accessible web design - zioncore.com
 
while we're all posting code, here's something i came up with a while ago... it allows for 3 - just change the variable.

Code:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "[URL unfurl="true"]http://www.w3.org/TR/html4/strict.dtd">[/URL]

<html>
<head>
<title>Enabling Certain Amount of Checkboxes</title>

<script language="javascript" type="text/javascript">
<!--

var totalCBs = 0;
var maxChecked = 3;

function keepTrack(c) {
    totalCBs += c.checked ? 1 : -1;
    enableDisable( c.form, totalCBs == maxChecked );
}

function enableDisable(f, b) {
    var e = f.elements;
	for (var i = 0; i < e.length; i++) {
        if (e[i].type == 'checkbox' && !e[i].checked) e[i].disabled = b;
	}
}

-->
</script>

<style type="text/css">

</style>

</head>

<body>

	<form name="f">
		<input type="checkbox" name="cb1" onclick="keepTrack(this);" /> Checkbox 1<br />
		<input type="checkbox" name="cb2" onclick="keepTrack(this);" /> Checkbox 2<br />
		<input type="checkbox" name="cb3" onclick="keepTrack(this);" /> Checkbox 3<br />
		<input type="checkbox" name="cb4" onclick="keepTrack(this);" /> Checkbox 4<br />

		<input type="checkbox" name="cb5" onclick="keepTrack(this);" /> Checkbox 5<br />
		<input type="checkbox" name="cb6" onclick="keepTrack(this);" /> Checkbox 6<br />
		<input type="checkbox" name="cb7" onclick="keepTrack(this);" /> Checkbox 7<br />
	</form>

</body>

</html>

*cLFlaVA
----------------------------
[tt]I already made like infinity of those at scout camp...[/tt]
[URL unfurl="true"]http://www.coryarthus.com/[/url]
[banghead]
 
well guys, what can i say.

Just got back to find all the helpful posts.

Really appreciate it, will let you know how i get on.

Stars all round

Thank you very much

Soph x
 
Hi guys,

i've put together my script from all your helpful posts and would like to add one small function to it.

Heres what i have so far
Code:
<script language="javascript" type="text/javascript">
<!--

var totalCBs = 0;
var maxChecked = 4;

function keepTrack(c) {
    totalCBs += c.checked ? 1 : -1;
    enableDisable( c.form, totalCBs == maxChecked );
}

function enableDisable(f, b) {
    var e = f.elements;
    for (var i = 0; i < e.length; i++) {
        if (e[i].type == 'checkbox' && !e[i].checked) e[i].disabled = b;
    }
}

-->
</script>

and

Code:
<form action="add3.php" method="post" onsubmit="">
        <input type="checkbox" name="cb1" value="HSC358" onclick="keepTrack(this);" /> HSC358<br />
        <input type="checkbox" name="cb2" value="HSC360" onclick="keepTrack(this);" /> HSC360<br />
        <input type="checkbox" name="cb3" value="HSC333" onclick="keepTrack(this);" /> HSC333<br />
        <input type="checkbox" name="cb4" value="HSC347" onclick="keepTrack(this);" /> HSC347<br />
        <input type="checkbox" name="cb5" value="HSC358" onclick="keepTrack(this);" /> HSC358<br />
        <input type="checkbox" name="cb6" value="HSC311" onclick="keepTrack(this);" /> HSC311<br />
  <input type="hidden" name="userid" value="<?= $userid ?>">
  <input type="hidden" name="award" value="<?= $award ?>">
  <input type="submit" name="add" value="Proceed">
</form>

How would i add to the jav so that the user cannot proceed until they have selected 4 checkboxes?


Sophie Lois
 
cLflava,

that works, thank you.

How would i make it trigger an alert telling the user why they cannot proceed.

Thanks again

Soph
 
i would do a function so your html isn't so messy.

form:
Code:
<form action="add3.php" method="post" onsubmit="return doSubmit();">

function:
Code:
function doSubmit() {
    if (totalCBs!=maxChecked) {
        alert('need to select ' + maxChecked + ' checkboxes');
        return false;
    }
    return true;
}

*cLFlaVA
----------------------------
[tt]I already made like infinity of those at scout camp...[/tt]
[URL unfurl="true"]http://www.coryarthus.com/[/url]
[banghead]
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top