Making sure at least one checkbox is checked

后端 未结 9 798
天命终不由人
天命终不由人 2020-11-27 16:39

I have a form with multiple checkboxes and I want to use JavaScript to make sure at least one is checked. This is what I have right now but no matter what is chosen an alert

9条回答
  •  伪装坚强ぢ
    2020-11-27 17:15

    You should avoid having two checkboxes with the same name if you plan to reference them like document.FC.c1. If you have multiple checkboxes named c1 how will the browser know which you are referring to?

    Here's a non-jQuery solution to check if any checkboxes on the page are checked.

    var checkboxes = document.querySelectorAll('input[type="checkbox"]');
    var checkedOne = Array.prototype.slice.call(checkboxes).some(x => x.checked);
    

    You need the Array.prototype.slice.call part to convert the NodeList returned by document.querySelectorAll into an array that you can call some on.

提交回复
热议问题