Checkbox Limit using dynamic field name

Discussion in 'JavaScript' started by jntwebdesigns, Apr 13, 2008.

  1. #1
    I found a checkbox limit javascript that works great, but I need to make it dynamic (more than one checkbox group). The original script looks like this:

    function chkcontrol(j) {
    var total=0;
    for(var i=0; i < document.form1.ckb.length; i++){
    if(document.form1.ckb[i].checked){
    total =total +1;}
    if(total > 3){
    alert("Please Select only three") 
    document.form1.ckb[j].checked = false ;
    return false;
    }
    }
    } 
    Code (markup):
    With the call looking like this:

    ><input type=checkbox name=ckb value=1 onclick=''chkcontrol(0)'';>
    HTML:
    I am trying to use the same script for different checkboxes... like this:

    function chkcontrol(j, limit, name) {
    var total=0;
    
    for(var i=0; i < document.form1." + name + ".length; i++){
    if(document.form1.name[i].checked){
    total =total +1;}
    if(total > limit){
    alert("Please Select only " + limit) 
    document.form1.name[j].checked = false ;
    return false;
    }
    }
    } 
    Code (markup):
    But I donot know how to get the field name to recognize in the script???
     
    jntwebdesigns, Apr 13, 2008 IP
  2. Logic Ali

    Logic Ali Well-Known Member

    Messages:
    170
    Likes Received:
    5
    Best Answers:
    0
    Trophy Points:
    108
    #2
    function chkControl(box, limit)
    {
     var cbArray=box.form[box.name];
     
     for(var i=0, count=0, len=cbArray.length; i<len; i++)
      if(cbArray[i].checked)
       count++; 
       
     if(count > limit)
     {
      box.checked=false;
      alert('Check no more than '+limit);
     }    
    }
    
    Code (markup):
    onclick="chkControl(this, 4)"
    Code (markup):
    All checkboxes must be within a form.
     
    Logic Ali, Apr 14, 2008 IP