javascript - 检查所有可见的下拉菜单是否为空 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试用此代码的链接。
谢谢。
解决方案
您正在使用 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 循环由于下拉列表之一中的非空值而中断。
推荐阅读
- python - 这个语句真的初始化了python中的变量类型吗?
- r - 如何对变量中日期范围内的每一行求和
- python - 非常低的回归分数和超低的分类分数
- excel - 将工作表复制到新工作簿并保存
- python - 使用 Python 和 Ray 读取大型 XML 文件
- python - 从预定义集中为 scipy.optimize 选择变量
- javascript - Centrifuge-js 使用用户脚本读取公共频道
- c++ - 从 MATLAB 代码和 MEX 文件和 dll 文件生成 C/C++ 代码
- r - R pivot_longer():tidyr 宽到长操作反向枢轴摘要到单个值
- javascript - 如何在发票中获取单个产品的多个 sku - jquery