【问题标题】:Why is the checked checkbox null?为什么选中的复选框为空?
【发布时间】:2021-01-18 06:14:13
【问题描述】:

下面是一个非常简单的javascript函数。当我单击该按钮时,它应该向我显示选中复选框的值,但它没有在控制台中打印出错误,说 checkedValue 为空?

我尝试遍历复选框并获得选中的复选框,但我得到了同样的错误。非常感谢您的帮助!

<body>
<p id='txt'>here: </p>
<button id="btn" type="button" onclick="ok" >Click </button>

<input type="checkbox" class="ckb" value="1">one
<input type="checkbox" class="ckb" value="2">two 
<input type="checkbox" class="ckb" value="3">three
<script>
var checkedValue = document.querySelectorAll('.ckb').checked;

document.getElementById('btn').addEventListener('click', function(){
document.getElementById('txt').innerText = checkedValue.value ;
});
</script>
</body>

遍历复选框

 var checkedValue; 
 var inputElements = document.querySelectorAll('.ckb');
 for(var i=0; i < inputElements.length; i++){
    if(inputElements[i].checked===true){
         checkedValue = inputElements[i];
         break;
    }
}

【问题讨论】:

  • checkedValue 是一个布尔值,表示第一个 .ckb 元素的检查状态,并且没有 value 属性。你还没有显示你尝试的循环,你想做什么?
  • 您需要参考document.querySelector('.ckb')。 Also.checked 给出一个布尔值
  • @DavidsaysreinstateMonica 我用循环部分更新了帖子。我正在尝试获取选中复选框的值。
  • 请分享完整和准确的错误信息,以及您的调试尝试

标签: javascript html checkbox


【解决方案1】:

经过一些小的调整,这应该就是您想要的。


<body>
    <p id='txt'>here: </p>
    <button id="btn" type="button">Click </button>
    
    <input type="checkbox" class="ckb" value="1">one
    <input type="checkbox" class="ckb" value="2">two 
    <input type="checkbox" class="ckb" value="3">three
    <script>

    document.getElementById('btn').addEventListener('click', function()
    {
        var chkbxElements = document.getElementsByClassName("ckb");

        for (element of chkbxElements)
        { 
           if (element.checked)
           {
                document.getElementById('txt').innerText = `here: ${element.value}`;
           }
        } 

    });

    </script>
</body>

【讨论】:

  • 当然,很高兴我能帮上忙!如有任何其他问题,请联系我。
【解决方案2】:

直接解决你的问题,问题出在代码上:

// this line returns a NodeList of all elements matching the
// supplied CSS selector ('.ckb'), this NodeList has no
// 'checked' property, and so will ultimately return
// undefined.
var checkedValue = document.querySelectorAll('.ckb').checked;

document.getElementById('btn').addEventListener('click', function(){

  // here you try to access the 'value' property of the undefined
  // Object returned earlier, which returns null:
  document.getElementById('txt').innerText = checkedValue.value ;
});

作为替代方案,我建议如下:

// using a const to declare the element, since it's unlikely
// you'll want to change which element triggers the function:
const button = document.getElementById('btn');

//here we bind the anonymous function of EventTarget.addEventListener()
// to the 'click' event upon that identified <button> element, using
// Arrow function syntax (since we don't require access to the
// 'this'):
button.addEventListener('click', (e) => {

  // here we retrieve all elements which are checked (using the
  // CSS pseudo-class ':checked') and have the class of 'ckb':
  let checked = document.querySelectorAll('.ckb:checked'),
    // retrieving the element into which the output should be
    // displayed:
    output = document.querySelector('#txt');

  // here we update the text-content (using the textContent property)
  // and set it equal to the results returned from:
    // first converting the NodeList of checked
    // into an Array, using Array.from(), using the
    // Array.prototype.map() method to iterate over that
    // Array:
  output.textContent = Array.from(checked).map(
    // returning the value of the element ('el'):
    (el) => el.value
  // joining those array elements together into a String, using
  // Array.prototype.join(), and appending a period for
  // grammatical correctness:
  ).join(', ') + '. ';
});

const button = document.getElementById('btn');

button.addEventListener('click', (e) => {
  let checked = document.querySelectorAll('.ckb:checked'),
    output = document.querySelector('#txt');
  output.textContent = Array.from(checked).map(
    (el) => el.value
  ).join(', ') + '. ';
});
*,
 ::before,
 ::after {
  box-sizing: border-box;
  font-size: 1rem;
  line-height: 1.4;
  margin: 0;
  padding: 0;
}

#txt::before {
  content: 'Checked items: '
}

#txt:empty::before {
  color: #999;
  content: 'No items checked.';
}

input {
  margin-right: 0.5em;
}
<p id='txt'></p>
<button id="btn" type="button">Click</button>
<label>
  <input type="checkbox" class="ckb" value="1">one
</label>
<label>
  <input type="checkbox" class="ckb" value="2">two 
</label>
<label>
  <input type="checkbox" class="ckb" value="3">three
</label>

JS Fiddle demo.

请注意,我还将每个 &lt;input&gt; 元素包装在 &lt;label&gt; 元素中,以便单击与每个 &lt;input&gt; 关联的文本也会切换该元素的选中状态。

使用 CSS 生成的内容,我冒昧地给出了当前状态的指示;当&lt;p id="txt"&gt; 元素为空(匹配:empty 伪类,甚至不包含空格)时,它会显示消息“未检查项目”),这可能(也可能不)代表用户体验/界面改进,但要根据自己的喜好进行调整。

我们进一步将事件绑定从 HTML 标记中移出,以减少该标记中的混乱,并减少页面未来维护时的复杂性。

当然,您可以将change 事件绑定到&lt;input&gt; 元素本身:

const inputs = document.querySelectorAll('.ckb'),
  output = () => {
    let results = document.querySelector('#txt'),
      checked = Array.from(inputs).filter(
        (el) => el.checked
      );

    results.textContent = checked.length === 0 ? '' : checked.map(
      (el) => el.value
    ).join(', ') + '. ';
  };

inputs.forEach(
  (el) => el.addEventListener('change', output)
);

// getting a NodeList of all elements matching the supplied
// CSS selector:
const inputs = document.querySelectorAll('.ckb'),
      // defining the function to bind as the event-
      // handler, using Arrow function syntax:
      output = () => {

        // retrieving the element to which the results
        // should be inserted:
        let results = document.querySelector('#txt'),

        // using Array.from() to convert the 'inputs'
        // variable to an Array, and then calling
        // Array.prototype.filter() to filter that
        // Array returning a new one:
        checked = Array.from(inputs).filter(
          // 'el' refers to the current Array-element
          // (node) of the Array we're iterating over,
          // el.checked is a Boolean, and
          // Array.protoype.filter() retains those Array-
          // elements the assessment of which returns a
          // true/truthy value (discarding those which do
          // not):
          (el) => el.checked
        );

    // here we use a ternary - conditional operator - to first
    // check if the length of the checked Array is exactly zero;
    // if so we return an empty string; otherwise we return
    // the map of Array-element (node) values joined - as above -
    // with a comma and space, with an appended period:
    results.textContent = checked.length === 0 ? '' : checked.map(
      (el) => el.value
    ).join(', ') + '. ';
  };

// iterating over the NodeList of .ckb elements, with an
// Arrow function, and in each iteration we bind the 
// output() function as the event-handler for the 'change'
// event:
inputs.forEach(
  (el) => el.addEventListener('change', output)
);
*,
 ::before,
 ::after {
  box-sizing: border-box;
  font-size: 1rem;
  line-height: 1.4;
  margin: 0;
  padding: 0;
}

#txt::before {
  content: 'Checked items: ';
}

#txt:empty::before {
  color: #999;
  content: 'No items checked.';
}
<p id='txt'></p>
<label>
  <input type="checkbox" class="ckb" value="1">one
</label>
<label>
  <input type="checkbox" class="ckb" value="2">two 
</label>
<label>
  <input type="checkbox" class="ckb" value="3">three
</label>

JS Fiddle demo.

参考资料:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-04-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多