在搜索时,如果没有匹配,该选项将被隐藏,但即使没有子选项匹配,optgroup仍然显示。如果没有选项匹配,如何隐藏 optgroup?
我已经尝试过解决这个问题,这是我尝试过的代码:jsfiddle
$("#uniAddressSearch").on("keyup", function (){
var value = $(this).val().toLowerCase();
$("#u-address option").filter(function (){
$(this).toggle($(this).text().toLowerCase().indexOf(value) > -1);
});
});
// &&
$("#u-address option").each(function() {
$(this).attr("data-search-term", $(this).text().toLowerCase());
});
$("#uniAddressSearch").on("keyup", function() {
var searchTerm = $(this).val().toLowerCase();
$("#u-address option").each(function() {
if ($(this).filter("[data-search-term *= " + searchTerm + "]").length > 0 || searchTerm.length < 1) {
$(this).show();
} else {
$(this).hide();
}
}); //end Option each
}); //end search
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="address-listing">
<input type="text" name="addressSearch" id="uniAddressSearch" placeholder="Select Location(s) Individually" class="form-control" />
</div>
<div class="u-address-fields">
<select size="15" multiple="multiple" class="show" id="u-address">
<optgroup class="og-swe" label="Swedish Cars">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
</optgroup>
<optgroup class="og-ger" label="German Cars">
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
<option value="bmw">BMW</option>
</optgroup>
<optgroup class="og-ita" label="Italian Cars">
<option value="ferrari">Ferrari</option>
<option value="lamborghini">Lamborghini</option>
</optgroup>
</select>
</div>
最佳答案
更改这部分代码,
来自:
$("#u-address option").each(function() {
if ($(this).filter("[data-search-term *= " + searchTerm + "]").length > 0 || searchTerm.length < 1) {
$(this).show();
} else {
$(this).hide();
} }); //end Option each
致:
$("#u-address optgroup").show();
$("#u-address option").each(function() {
if ($(this).filter("[data-search-term *= " + searchTerm + "]").length > 0 || searchTerm.length < 1) {
$(this).show();
} else {
$(this).hide();
var count = $(this).parent("optgroup").find("option:visible").length;
if(count == 0)
$(this).parent("optgroup").hide();
} }); //end Option each
关于javascript - jquery 搜索过滤器 - 如果搜索不匹配,选项将被隐藏,但 optgroup 仍显示,如何隐藏 optgroup,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54400537/