jQuery 如何检查表单循环中的单选按钮和复选框是否被选中?

How to check whether a radio buttons and checkboxes are selected in form loop in jQuery?

我正在制作我的第一个 js 插件来验证 html 表单。我已经为文本字段弄清楚了,但是在选择验证单选按钮和复选框的最佳方式时遇到了一些问题。由于可以有多个单选组,每个组都有许多单选按钮。我正在做的是围绕表单元素循环,如下所示。

 _self.on("submit", function(event) {
                console.log('form submitted ');
                _self.find('.'+settings.errorClass).each(function(){
                    let type = $(this).attr('type');
                    let val = $(this).val();
                    validate(type, val);
                });
validate = function(type, val) {
            console.log(type);
            switch (type) {
                case 'text':
                    validateText(val);
                    break;
                case 'radio':
                    validaRadio(val);
                    break;
             case 'checkbox':
                validaCheckbox(val);
                break;
                default:

            }

现在在上面的代码中,为我不想要的每个组中的每个单选按钮调用了 validaRadio 函数。我想按组(名称)验证单选按钮。因此,如果有两个单选组,每个单选组都有四个单选按钮,那么每个单选组应该调用 validateRadio 函数两次,而不是八次。 如果你们对上述问题有更好的解决方案,请告诉我。

你的方法没有必要。您所要做的就是为每组单选按钮获取一个集合,并检查选中项目的 length 并查看该长度是否为 0。

var groups = Array.prototype.slice.call(document.querySelectorAll("fieldset"));

// Set up an event callback that checks validity
document.querySelector("button").addEventListener("click", function(){
  console.clear();
  // Loop over the button groups (each group is in a container element of some kind - a fieldset here)
  groups.forEach(function(g){
    // Look in the container element for the checked buttons in the group
    // and see if the amount of checked buttons is zero
    if(g.querySelectorAll("input[name^='group']:checked").length === 0){
     // If so, none were selected in that group
     console.log("You must select a choice in " + g.dataset.group);
    }
  });
});
<fieldset data-group="Group One">
  <input type="radio" name="group1" value="One"> One
  <input type="radio" name="group1" value="Two"> Two
  <input type="radio" name="group1" value="Three"> Three
  <input type="radio" name="group1" value="Four"> Four
</fieldset>
<fieldset data-group="Group Two">
  <input type="radio" name="group2" value="One"> One
  <input type="radio" name="group2" value="Two"> Two
  <input type="radio" name="group2" value="Three"> Three
  <input type="radio" name="group2" value="Four"> Four
</fieldset>
<button type="button">Check</button>

为您已经发送给验证者的名称创建一个 checkedRadioNames 数组。如果有名称已验证的单选按钮,请跳过它。

_self.on("submit", function(event) {
  console.log('form submitted ');
  const checkedRadioNames = [];
  _self.find('.'+settings.errorClass).each(function(){
    const type = $(this).attr('type');
    const val = $(this).val();
    if (type === 'radio') {
      const name = $(this).attr('name');
      if (checkedRadioNames.includes(name)) return;
      validaRadio(val, name);
    } else validate(type, val);
  });