Javascript 选择另一个复选框时如何启用/禁用复选框?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6060681/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 20:04:38  来源:igfitidea点击:

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

javascriptcheckbox

提问by dinah

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! –

我了解了如何在选中一个复选框时选中/取消选中或隐藏/显示,但我要查找的是当用户单击 Fastfood 时我有 5 个复选框 Fastfood、Catering、Carryout、Delivery 和 Bar,其余复选框在用户选中时被禁用餐饮,休息被禁用,但当用户检查结转只有快餐和餐饮被禁用。然后当用户取消选中时,所有复选框都返回启用/显示。谢谢!——

Here my code:

这是我的代码:

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


       if (document.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

采纳答案by dinah

All in all, not too difficult.

总而言之,难度不大。

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

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

HTML:

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:

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 checkedDOM property.
  2. I'm traversing the HTMLFormElement.elementscollection to easily access the checkboxes.
  3. I'm setting the disabledDOM property to "disabled" on the checkbox if it's not the target checkbox.
  4. I'm setting the disabledDOM 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 onchangehandler.
  6. This code shouldwork 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.
  1. 我正在使用事件委托来最小化事件处理程序的数量。表单侦听冒泡的单击事件,然后根据单击的元素及其checkedDOM 属性调用函数。
  2. 我正在遍历HTMLFormElement元素集合以轻松访问复选框。
  3. disabled如果复选框不是目标复选框,我将在复选框上将 DOM 属性设置为“禁用”。
  4. disabled如果没有选中复选框,我将在复选框上将 DOM 属性设置为 ""(一个空字符串)。
  5. 如果用户通过选项卡/输入或通过onchange处理程序的其他方法选择复选框,这也适用。
  6. 这段代码应该可以在 IE 中工作,尽管我在工作中通过 Wine 使用 IE 时遇到了一些严重的问题,所以我必须稍后进行测试。
  7. 它使用“黑名单”,这是一个数组,其中包含单击相应复选框时不想启用的复选框的 ID。

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

如果您正在寻找任何进一步的信息,请告诉我。

回答by megakorre

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

希望有帮助

回答by svmaustin

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.

使用框架或工具包(如 jQuery)将使生活更轻松,但在继续使用工具包之前,最好先了解如何使用 javascript 操作 DOM。就像在使用计算器之前学习添加一样。

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?".

处理此问题的最佳方法是查看复选框的状态。if(document.myform.box2.checked == true),然后根据复选框的状态做出决定。您上面的函数只是修改复选框而不知道它们的状态。最好将 (this) 传递给函数,然后遍历 DOM。当它作为参数进入函数时,“this”将是复选框。所以你的函数会说“好吧,我已经把复选框“1”传递给了我,现在我的其他复选框的状态是什么?”。

回答by Ira Rainey

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

可以为此使用 jQuery,它(可能)会让您的生活更轻松。查看这些关于如何实现您想要的(使用 jQuery)的文章:

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

使用 JQUERY 显示/隐藏基于复选框选择的表单元素

Checkboxes + Jquery hide/show

复选框 + Jquery 隐藏/显示

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

注意:其他框架可用。根据个人口味选择。

回答by Symfony

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>

回答by shareef

js fiddle demo

js小提琴演示

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>