仅使用Vanilla JS满足特定条件后禁用复选框

时间:2018-08-02 19:43:57

标签: javascript html checkbox

我正在尝试创建一个功能,该功能将在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>

3 个答案:

答案 0 :(得分:0)

有几个错误,所以这可以解决问题

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
  })
}

答案 1 :(得分:0)

首先要注意几件事:

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 :(得分:0)

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

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个已选中的复选框