首页 > 解决方案 > 检查所有可见的下拉菜单是否为空 jQuery

问题描述

我有五个checkboxes连接到隐藏的下拉菜单。

单击复选框时会显示隐藏的下拉菜单。

<input type="checkbox" id="chb1" class="chk-group" name="chb" value="chb1">
<label for="chb1"> 1 </label>
<select id="slct-1">
  <option value="">Default</option>
  <option value="1">1</option>
  <option value="2">2</option>
  <option value=3>3</option>
</select><br>

<input type="checkbox" id="chb2" class="chk-group" name="chb" value="chb2">
<label for="chb2"> 2 </label>
<select id="slct-2">
  <option value="">Default</option>
  <option value="1">1</option>
  <option value="2">2</option>
  <option value=3>3</option>
</select><br>

<input type="checkbox" id="chb3" class="chk-group" name="chb" value="chb3">
<label for="chb3"> 3 </label>
<select id="slct-3">
  <option value="">Default</option>
  <option value="1">1</option>
  <option value="2">2</option>
  <option value=3>3</option>
</select><br>

<input type="checkbox" id="chb4" class="chk-group" name="chb" value="chb4">
<label for="chb4"> 4 </label>
<select id="slct-4">
  <option value="">Default</option>
  <option value="1">1</option>
  <option value="2">2</option>
  <option value=3>3</option>
</select><br>

<input type="checkbox" id="chb5" class="chk-group" name="chb" value="chb5">
<label for="chb5"> 5 </label>
<select id="slct-1">
  <option value="">Default</option>
  <option value="1">1</option>
  <option value="2">2</option>
  <option value=3>3</option>
</select><br> 

我想检查所有可见的下拉菜单是否为空。

我在下面尝试了这段代码,它可以工作,但不是它应该做的,

此代码的结果是- 当我选择复选框 1、2 和 3 时,然后更改了 3 的下拉选择,即使 1 和 2 的下拉选择为空,它也会立即返回 true。

预期结果- 只有当所有可见下拉列表不为空时,它才应返回 true。

这是代码

$('input[name="chb"]').click(function(){
    checker();
  $('select[id^="slct-"]').change(function () {
      checker();
  });

});


function checker() {
  $('input[name="chb"]:checked').each(function () {
        var idnum = $(this).prop('id').replace(/[^\d.]/g, '');
        if (idnum != 1 || idnum != 2 || idnum != 19) {
            if ($('#slct-' + idnum + ' option:selected').val() === "") {
                $('span#text').text('False');
            } else if ($('#slct-' + idnum + ' option:selected').val() != "") {
                $('span#text').text('True');
            }
        }
   });
}

这是Codepen试用此代码的链接。

谢谢。

标签: javascripthtmljquery

解决方案


您正在使用 JQueryeach并将值写入输出,即span#text在每次迭代中,这将覆盖每次迭代中的值,最后一个值将被最终覆盖。我认为这里的简单修复之一是:

    var i=0;
     for i = 0, $('input[name="chb"]:checked').length {
          if ($('#slct-' + idnum + ' option:selected').val() !== "") 
                   break;
    }
    if( i=== $('input[name="chb"]:checked').length)
   {
        print true
        return 
    }else {
    print false;
    }
   }

如果找到非空值,这里的 for 循环将中断。如果所有值都为空,则在 for 循环完成后 i 的值将等于数组的长度,否则 for 循环由于下拉列表之一中的非空值而中断。


推荐阅读