【问题标题】:Disable checkboxes after a certain condition is met using only Vanilla JS仅使用 Vanilla JS 满足特定条件后禁用复选框
【发布时间】:2018-08-03 04:19:14
【问题描述】:

我正在尝试创建一个函数,该函数将在选中 5 个框后禁用表单中所有剩余的未选中复选框。

我能够提取值(使用 .length)来验证 5 个复选框实际上已被选中,但我无法将 disable() 函数正确连接到剩余的复选框。任何建议将不胜感激。

JS逻辑如下:

    document.addEventListener('DOMContentLoaded', () => {
       let Checkboxes = 
    document.querySelectorAll('input[type="checkbox"]').length <-verifies checkbox total;

    Checkboxes.addEventListener('click', (event)=>{
        event.preventDefault();
        checkboxLimiter();
    });
});

function checkboxLimiter() {
    let markedBoxCount = document.querySelectorAll('input[type="checkbox"]:checked').length; <-verifies "checked" checkbox total;

    if (markedBoxCount == 5){
        disable();
    }
}

function disable() {
    let unmarkedBoxCount = document.querySelectorAll('input[type="checkbox"]:not(:checked)') <-selector for remaining "unchecked" checkboxes;
   ;
    unmarkedBoxCount.disabled = true;

这里是 HTML 供参考:

<div id="strengthsJar">

        <div id="stJar">
            <p>Strategic Thinking</p>
            <label class="checkbox-inline" for="usertype"> <input
                type="checkbox" name="attribute" id="st-attribute" value="(1,1)"></label>

        </div>

        <div id="eJar">
            <p>Executing</p>
            <label class="checkbox-inline" for="usertype"> <input
                type="checkbox" name="attribute" id="e-attribute" value="(1,-1)">
                Achiever
            </label>
        </div>

        <div id="rbJar">
            <p>Relationship Building</p>
            <label class="checkbox-inline" for="usertype"> <input
                type="checkbox" name="attribute" id="rb-attribute" value="(-1,1)">
                Adaptability
            </label>
        </div>
        <div id="iJar">
            <p>Influencing</p>
            <label class="checkbox-inline" for="usertype"> <input
                type="checkbox" name="attribute" id="i-attribute" value="(-1,-1)">
                Activator

            </label>
        </div>
    </div>

【问题讨论】:

    标签: javascript html checkbox


    【解决方案1】:

    好的,先做几件事:

    1.)

     let Checkboxes = document.querySelectorAll('input[type="checkbox"]').length
    

    这样做,您会将 Checkboxes 变量设置为等于文档中所有复选框的数组长度的数字,而不是数组本身,因此您无法在数字上添加事件监听器。

    2.)

        Checkboxes.addEventListener('click', (event)=>{
            event.preventDefault();
            checkboxLimiter();
        });
    

    let unmarkedBoxCount = document.querySelectorAll('input[type="checkbox"]:not(:checked)') ;
    unmarkedBoxCount.disabled = true;
    

    您不能一次对整个 DOM 节点数组执行操作,您必须遍历它们并添加侦听器或逐个禁用它们。

    3.)

        Checkboxes.addEventListener('click', (event)=>{
        event.preventDefault();
        checkboxLimiter();
        });
    

    如果您在此处阻止默认操作,则无法选中该复选框。

    这是工作代码,一个区别是我在您选中其中两个复选框后禁用其余复选框,因为我不想添加更多复选框以保持示例简单。

    <!DOCTYPE html>
    <html lang="en">
    
    <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <meta http-equiv="X-UA-Compatible" content="ie=edge">
      <title>Document</title>
    </head>
    
    <body>
    
      <div id="strengthsJar">
    
        <div id="stJar">
          <p>Strategic Thinking</p>
          <label class="checkbox-inline" for="usertype">
            <input type="checkbox" name="attribute" id="st-attribute" value="(1,1)">
          </label>
    
        </div>
    
        <div id="eJar">
          <p>Executing</p>
          <label class="checkbox-inline" for="usertype">
            <input type="checkbox" name="attribute" id="e-attribute" value="(1,-1)"> Achiever
          </label>
        </div>
    
        <div id="rbJar">
          <p>Relationship Building</p>
          <label class="checkbox-inline" for="usertype">
            <input type="checkbox" name="attribute" id="rb-attribute" value="(-1,1)"> Adaptability
          </label>
        </div>
        <div id="iJar">
          <p>Influencing</p>
          <label class="checkbox-inline" for="usertype">
            <input type="checkbox" name="attribute" id="i-attribute" value="(-1,-1)"> Activator
    
          </label>
        </div>
      </div>
      <script>
        document.addEventListener('DOMContentLoaded', () => {
          let Checkboxes = document.querySelectorAll('input[type="checkbox"]');
    
          for (let i = 0; i < Checkboxes.length; i++)
            Checkboxes[i].addEventListener('click', (event) => {
              checkboxLimiter();
            });
        });
    
        function checkboxLimiter() {
          let markedBoxCount = document.querySelectorAll('input[type="checkbox"]:checked').length;
    
          if (markedBoxCount == 2) {
            disable();
          }
        }
    
        function disable() {
          let unmarkedBoxCount = document.querySelectorAll('input[type="checkbox"]:not(:checked)');
          for (let i = 0; i < unmarkedBoxCount.length; i++)
            unmarkedBoxCount[i].disabled = true;
        }
      </script>
    </body>
    
    </html>

    【讨论】:

      【解决方案2】:

      有几个错误,所以这会起作用

      document.addEventListener('DOMContentLoaded', () => {
        // we need to get all checkbox elements, not its length
        let Checkboxes = document.querySelectorAll('input[type="checkbox"]')
      
        // Checkboxes is nodelist, so we need to add event listener 
        // on every element in it, like this for example
        Checkboxes.forEach( checkbox => {
          checkbox.addEventListener('click', (event)=>{
            checkboxLimiter();
          });
        });
      });
      
      function checkboxLimiter() {
        let markedBoxCount = document.querySelectorAll('input[type="checkbox"]:checked').length;
      
        if (markedBoxCount == 3){
          disable();
        }
      }
      
      function disable() {
        let unmarkedBoxCount = document.querySelectorAll('input[type="checkbox"]:not(:checked)');
      
        // same thing as Checkboxes
        unmarkedBoxCount.forEach(checkbox => {
          checkbox.disabled = true
        })
      }

      【讨论】:

        【解决方案3】:

        你的逻辑有一些错误 试试这个:

        let Checkboxes = document.querySelectorAll('input[type="checkbox"]'); 
        
        for(var i = 0; i < Checkboxes.length; i++) {
            Checkboxes[i].addEventListener('change', function() {
                checkboxLimiter(this);
            });
        }
        
        function checkboxLimiter(checkbox) {
            let markedBoxCount = 
                document.querySelectorAll('input[type="checkbox"]:checked').length
            if (markedBoxCount > 2){
                checkbox.checked = false;
            };
        };
        

        在这个例子中,我禁用了 2 个选中的复选框

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2011-12-28
          • 2014-02-18
          • 1970-01-01
          • 2019-05-06
          • 1970-01-01
          • 1970-01-01
          • 2013-02-21
          • 1970-01-01
          相关资源
          最近更新 更多