如何只显示那些选中的选项,而隐藏所有未选中的选项?
我的代码只显示复选框,而不是标签。
$("#checked_show").click(function() {
$("input").hide();
$("label").hide();
$("input:checked").show();
});<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" name="locationthemes" id="checkbox-1" value="2" class="custom" />
<label for="checkbox-1">Castle</label>
<input type="checkbox" name="locationthemes" id="checkbox-2" value="3" class="custom" />
<label for="checkbox-2">Barn</label>
<br /><br />
<input type="checkbox" name="location" id="checkbox-3" value="5" class="custom" />
<label for="checkbox-3">Restaurant</label>
<input type="checkbox" name="location" id="checkbox-4" value="8" class="custom" />
<label for="checkbox-4">Bar</label>
<br /><br />
<button id="checked_show">Show only Checked</button>
如何只显示那些选中的选项,而隐藏所有未选中的选项?
我的代码只显示复选框,而不是标签。
发布于 2020-06-07 22:24:52
您应该使用:checked来选择选中的输入,并使用:not()对其求反,还可以使用.next()来隐藏必须遍历所有元素并选择下一个元素的标签,下面是一个有效的代码片段:
$("#checked_show").click(function () {
if ($("input[type='checkbox']:checked").length) {
$("input[type='checkbox']:not(:checked)").each(function (idx, el) {
$(el).next().hide();
$(el).hide();
});
} else {
console.log('Please select an input!');
}
});<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" name="locationthemes" id="checkbox-1" value="2" class="custom" />
<label for="checkbox-1">Castle</label>
<input type="checkbox" name="locationthemes" id="checkbox-2" value="3" class="custom" />
<label for="checkbox-2">Barn</label>
<br /><br />
<input type="checkbox" name="location" id="checkbox-3" value="5" class="custom" />
<label for="checkbox-3">Restaurant</label>
<input type="checkbox" name="location" id="checkbox-4" value="8" class="custom" />
<label for="checkbox-4">Bar</label>
<br /><br />
<button id="checked_show">Show only Checked</button>
发布于 2020-06-07 22:27:07
您可以结合使用input:checked和:not()来选择未检查的输入。
$("#checked_show").click(function() {
$("input:not(:checked)").each((i, el) => {
$(el).next().hide();
$(el).hide();
});
});<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" name="locationthemes" id="checkbox-1" value="2" class="custom" />
<label for="checkbox-1">Castle</label>
<input type="checkbox" name="locationthemes" id="checkbox-2" value="3" class="custom" />
<label for="checkbox-2">Barn</label>
<br /><br />
<input type="checkbox" name="location" id="checkbox-3" value="5" class="custom" />
<label for="checkbox-3">Restaurant</label>
<input type="checkbox" name="location" id="checkbox-4" value="8" class="custom" />
<label for="checkbox-4">Bar</label>
<br /><br />
<button id="checked_show">Show only Checked</button>
https://stackoverflow.com/questions/62246692
复制相似问题