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?
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?
Yeah, I think you can. I'm not sure I fully understand it, but try this:
Code:<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>Edit: For some reason I wrote tags() instead of getElementsByTagName()
- Mike
Not quite.
It only allows me to select the first two... not any two.
Oh I see. This should work:
Code:<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>
- Mike
jc_gmk (08-20-2008)
Perfect, thanks!!
Following on from this...
If the form is generated dynamically this script doesn't work
e.g.
Two checkboxes should be ticked at all times - This info is then stored in a database for next time the page is accessed.PHP Code:<form name="myForm">
<?
while ($info = mysql_fetch_array($result))
{ ?>
<input type="checkbox"<? if ($info['something'] == "T") { echo ' checked="checked"' } ?> />
<?
} ?>
</form>
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.
Bookmarks