PDA

View Full Version : Limit users choices with a checkbox



jc_gmk
08-20-2008, 01:46 PM
Is it possible that if i have say 10 checkboxes in a form that i can limit the selection by the user to just 2?
Maybe when the third is selected the user gets an alert?

mburt
08-20-2008, 02:02 PM
Yeah, I think you can. I'm not sure I fully understand it, but try this:


<form name="myForm">
<input type="checkbox">
<input type="checkbox">
<input type="checkbox" class="disable">
<input type="checkbox" class="disable">
<input type="checkbox" class="disable">
<input type="checkbox" class="disable">
<input type="checkbox" class="disable">
<input type="checkbox" class="disable">
<input type="checkbox" class="disable">
<input type="checkbox" class="disable">
</form>
<script type="text/javascript">
var disable = function() {
var all = document.forms["myForm"].getElementsByTagName("input");
for (var i = all.length-1;i > -1;--i) {
if (all[i].className == "disable") {
all[i].onclick = function() {
alert("Some message");
return false;
};
};
};
}();
</script>

For some reason I wrote tags() instead of getElementsByTagName()

jc_gmk
08-20-2008, 02:39 PM
Not quite.

It only allows me to select the first two... not any two.

mburt
08-20-2008, 03:07 PM
Oh I see. This should work:


<form name="myForm">
<input type="checkbox">
<input type="checkbox">
<input type="checkbox">
<input type="checkbox">
<input type="checkbox">
<input type="checkbox">
<input type="checkbox">
<input type="checkbox">
<input type="checkbox">
<input type="checkbox">
</form>
<script type="text/javascript">
Array.prototype.remove = function(from, to) {
var rest = this.slice((to || from) + 1 || this.length);
this.length = from < 0 ? this.length + from : from;
return this.push.apply(this, rest);
};
var disable = function() {
var all = document.forms["myForm"].getElementsByTagName("input"),
clicked = [], count = 0;
for (var i = all.length-1;i > -1;--i) {
all[i].onmousedown = function() {
if (clicked.length < 2) {
if (!this.checked) {
clicked[count] = this;
this.c = count;
++count;
} else {
clicked.remove(this.c);
--count;
};
} else {
if (!this.checked) {
alert("message");
return false;
} else {
clicked.remove(this.c);
--count;
};
};
};
};
}();
</script>

jc_gmk
08-20-2008, 03:33 PM
Perfect, thanks!!

jc_gmk
08-21-2008, 03:22 PM
Following on from this...

If the form is generated dynamically this script doesn't work

e.g.


<form name="myForm">
<?
while ($info = mysql_fetch_array($result))
{ ?>
<input type="checkbox"<? if ($info['something'] == "T") { echo ' checked="checked"' } ?> />
<?
} ?>
</form>


Two checkboxes should be ticked at all times - This info is then stored in a database for next time the page is accessed.

With the current code you gave me, the page shows two boxes ticked, but allows me to select a further two boxes until the alert is displayed.

Hope this makes sense.