开发者

How do I enable/disable checkboxes when another checkbox is selected?

I got on how to check/unchecked or hide/show when one checkbox is checked but what im looking for is when I have 5 checkboxes Fastfood, Catering, Carryout, Delivery and Bar when user clicked Fastfood ,rest checkboxes are disable, when user checked Catering, rest are disable but when user checked Carryout only Fastfood and Catering are disable. Then when user unchecked, all checkboxes back to enable/show. thanks! –

Here my code:

<script type="text/javascript">
function HideOrShowStuff(controlToHide1)
{


       if (documen开发者_Go百科t.getElementById)
   {
          if(controlToHide1==1)
      {
      document.getElementById('2').disabled=true;
        document.getElementById('3').disabled = true;
          document.getElementById('4').disabled = true;
           document.getElementById('5').disabled = true;
           document.getElementById('1').disabled = false;
             }
        if(controlToHide1==2)
      { 
         document.getElementById('1').disabled=true;
        document.getElementById('2').disabled = false;
          document.getElementById('4').disabled = true;
           document.getElementById('5').disabled = true;
           document.getElementById('3').disabled = true;
              }
                  if(controlToHide1==3)
      { 
          document.getElementById('1').disabled=true;
        document.getElementById('2').disabled = true;
          document.getElementById('4').disabled = false;
           document.getElementById('5').disabled = false;
           document.getElementById('3').disabled = false;
              }
                  }
        }

</script>

 Type of restaurant are you?<br /> <br /> 
<input type="checkbox" name="restaupop1"  id="1"value="fastfood" onclick="HideOrShowStuff(1)"    <?PHP print $fastfood_status; ?>> Fast Food/Drive Thru  <br />
<input type="checkbox" name="restaupop2" id="2"value="catering"  onclick="HideOrShowStuff(2); setVisible('restaubar');"   <?PHP print $catering_status; ?>> Catering<br />
<input type="checkbox"  name="restaupop3" id="3" value="carryout"  onclick="HideOrShowStuff(3)"   <?PHP print $carryout_status; ?>> Carry-Out<br />
<input type="checkbox" name="restaupop4" id="4"value="delivery"   onclick="setVisible('barpop1');"  <?PHP print $delivery_status; ?>> Delivery<br />
<input type="checkbox" name="restaupop5" id="5"value="bargrill" onclick="setVisible('restaubar');"     <?PHP print $bargrill_status; ?>>Bar/Grill


All in all, not too difficult.

http://jsfiddle.net/A5TGf/19/

HTML:

<form action="./" id="checkForm" method="post">
    <fieldset>
        <label for="foo">foo</label>
        <input type="checkbox" id="foo" value="foo" />
        <label for="bar">bar</label>
        <input type="checkbox" id="bar" value="bar" />
        <label for="baz">baz</label>
        <input type="checkbox" id="baz" value="baz" />
    </fieldset>
</form>

JS:

var form = document.getElementById("checkForm");
form.onclick = delegateFormClick;

addChangeHandlers(form);

function addChangeHandlers(form)
{
   for(var i=0;i<form.elements.length;i++)
   {
       var element = form.elements[i];
       if(element.tagName === "INPUT" && element.type === "checkbox")
       {
           if(!element.onchange)
           {
               element.onchange = checkBoxChanged;   
           }
       }
   }  
}

function delegateFormClick(evt)
{
    var target;
    if(!evt)
    {
        //Microsoft DOM
        target = window.event.srcElement;
    }else if(evt)
    {
        //w3c DOM
        target = evt.target;
    }
    if(target.nodeType === 1 && target.tagName === "INPUT" && target.type === "checkbox")
    {
        if(target.checked)
        {
            disableCheckBoxes(target.id, document.getElementById("checkForm"));
        }else if(!target.checked)
        {
            enableCheckBoxes(document.getElementById("checkForm"));
        }  
    }
}

function checkBoxChanged()
{
    if(this.checked)
    {
       disableCheckBoxes(this.id, document.getElementById("checkForm"));
    }else if(!this.checked)
    {
        enableCheckBoxes(document.getElementById("checkForm"));  
    }
}

function disableCheckBoxes(id, form)
{
    var blacklist = [];
    if(id)
    {
        switch(id)
        {
            case "foo":
            blacklist = ["bar", "baz"];
            break;
            case "bar":
            blacklist = ["foo"];
            break;
            case "baz":
            blacklist = ["foo", "bar"];
            break;
        }   
    }else
    {
        throw new Error("id is needed to hard-wire input blacklist");   
    }
    for(var i=0;i<blacklist.length;i++)
    {
        var element = document.getElementById(blacklist[i]);
        if(element && element.nodeType === 1)
        {
            //check for element
            if(element.tagName === "INPUT" && element.type === "checkbox" && !element.checked)
            {
                element.disabled = "disabled";
            }
        }else if(!element || element.nodeType !== 1)
        {
            throw new Error("input blacklist item does not exist or is not an element");
        }
    }   
}

function enableCheckBoxes(form)
{
    for(var i=0;i<form.elements.length;i++)
    {
        var element = form.elements[i];
        if(element.tagName === "INPUT" && element.type === "checkbox" && !element.checked)
        {
            element.disabled = "";
        }
    }   
}

Some quick notes on what I'm doing:

  1. I'm using event delegation to minimize the amount of event handlers. The form listens for a click event bubbling up, then calls a function depending on which element was clicked and its checked DOM property.
  2. I'm traversing the HTMLFormElement.elements collection to easily access the checkboxes.
  3. I'm setting the disabled DOM property to "disabled" on the checkbox if it's not the target checkbox.
  4. I'm setting the disabled DOM property to "" (an empty string) on the checkbox if no checkboxes are checked.
  5. This also works if the user selects the checkbox by tabbing/entering or another method via the onchange handler.
  6. This code should work in IE, though I'm having some serious problems with IE via Wine at work, so I'll have to test later.
  7. It uses a "blacklist", which is an array that contains ids to checkboxes you don't want enabled when the corresponding checkbox is clicked.

Let me know if you're looking for anything further.


so i havent completely gotten the logic you are trying to get here. But if you want to tell if the checkbox was unchecked or checked you can test it like this

 function hideOrShowStuff(box, controlToHide1) {
   if(box.checked) {
     // the hide logic
   } else {
    // the show logic
   }
 }

you also need to pass in the box reference like this

 onclick="HideOrShowStuff(this, 1)" 

hope that helps


You could use jQuery for this it would (probably) make your life easier. Check out these articles on how to achieve what you want (using jQuery):

USING JQUERY TO SHOW/HIDE FORM ELEMENTS BASED ON A CHECKBOX SELECTION

Checkboxes + Jquery hide/show

NB: Other frameworks are available. Take your pick according to personal tastes.


Using a framework or toolkit (like jQuery) will make life easier, but it's probably best to learn how the manipulate the DOM with javascript before moving on to a toolkit. Like learning to add before using a calculator.

The best way to deal with this is to look at the state of your checkboxes. if(document.myform.box2.checked == true), then make decisions based on the state of your checkboxes. The function you have above simply modifies the checkboxes without knowing anything about their state. It would be better to just pass (this) to the function, and then walk the DOM. "this" would be the checkbox when it comes into the function as a parameter. So your function would say "okay, I've got checkbox "1" passed to me, now what is the state of my other checkboxes?".


Try this code

 <script>
            function uncheck0(){
                for(var ii=1; ii<=3; ii++){
                    if(document.getElementById("q6_"+ii).checked==true){
                       document.getElementById("q6_"+ii).checked=false;
                    }
                }
            }
            function uncheck(id, from, to){
                for(var ii=from; ii<=to; ii++){
                    if(document.getElementById(id+ii).checked==true){
                       document.getElementById(id+ii).checked=false;
                    }
                }
            }
        </script>


js fiddle demo

function changeCheckBox() {
     try {

         var max = document.mainForm.serNo.length;
         var count = 0;

         for (var i = 0; i < max; i++) {
             if (document.mainForm.serNo[i].checked == true) {
                 count++;
                 serNoChecked = i;
             }
         }
         if (count == 1) {
             for (var i = 0; i < max; i++) {
                 if (document.mainForm.serNo[i].checked == false) {
                     document.mainForm.serNo[i].disabled = true;
                 }
             }
         } else if (count == 0) {
             for (var i = 0; i < max; i++) {
                 document.mainForm.serNo[i].disabled = false;
             }
         }

         if (null == max) return false;
         if (count == 0) {
             return true;
         } else if (count > 0) {
             return false;
         }

     } catch (e) {
         alert(e.message);
     }
 }



<form  name="mainForm" method="GET" action="Controller">
<TD STYLE="width:10px">
    <input type="checkbox" id="serNo" name="serNo" value="" onclick="changeCheckBox()" />
    <input type="checkbox" id="serNo" name="serNo" value="" onclick="changeCheckBox()" />
    <input type="checkbox" id="serNo" name="serNo" value="" onclick="changeCheckBox()" />
</TD>
</form>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜