faqts : Computers : Programming : Languages : JavaScript : Forms : Checkboxes

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

7 of 12 people (58%) answered Yes
Recently 5 of 10 people (50%) answered Yes

Entry

How can one checkbox check other checkboxes randomly?

Dec 6th, 2002 06:47
Jean-Bernard Valentaten, Gerald Maitz,


As far as I understood this question, what you want is to check one 
checkbox and have a random number of other checkboxes be checked by 
that action.
Well that shouldn't be too hard.
You need to build an array containing all the checkboxes that can be 
checked by random. Then you have to write a function that checks a 
random number of those boxes.
var checkAr = new Array('box1', 'box2', 'box3', ...);
function checkRandomly()
{
  //the next line generates a random number between 0 and 
  //checkAr.length - 1
  var intRandom = floor(Math.random() * checkAr.length);
  for (var i = 0; i <= intRandom; i++)
  {
    var myElem = document.myForm.elements[checkAr[i]]
    if (!myElem.checked)    
      myElem.checked = true;
    else
      myElem.checked = false;
  }
}
And finally in the onClick-Handler of the designated checkboxes you 
need to call the function:
<input type="checkbox" ... onClick="checkRandomly();">
That should do the trick.
HTH,
Jean