0

特定のチェックボックスがオンになっているかどうかに応じて div アイテムをフィルタリングしようとしています。デフォルトではすべてがオンになります。

フィルタリングを機能させることができましたが、結果が見つからない場合 (チェックボックスがチェックされていない場合) にエラーメッセージを追加するのに苦労しています。

結果が見つかりませんでした。フィルターをリセットして、もう一度検索してください

ここにコードを配置しましたhttp://jsfiddle.net/3WcDC/25/

私を助けることができる人に事前に感謝します。

HTML

<div id="CategoryContent">


<div class="product">Brand1</div>
<div class="product">Brand2</div>
<div class="product">Brand3</div>
<div class="product">Brand4</div>    


    <h2>Brands:</h2>
<input type="checkbox" name="brand" value="Brand1"/>Brand1 </br>
<input type="checkbox" name="brand" value="Brand2"/>Brand2 </br>
<input type="checkbox" name="brand" value="Brand3"/>Brand3 </br>    
<input type="checkbox" name="brand" value="Brand4"/>Brand4 </br>


</div>

フィルタリング用の JavaScript:

var $filters = $("input:checkbox[name='brand']").prop('checked', true); // start all checked
var $categoryContent = $('#CategoryContent div');
$filters.click(function() {
    // if any of the checkboxes for brand are checked, you want to show div's containing their value, and you want to hide all the rest.
    $categoryContent.hide();
    $filters.filter(':checked').each(function(i, el) {
        $categoryContent.filter(':contains(' + el.value + ')').show();
    });
});
4

1 に答える 1

2

必要なものは次のとおりです。

HTML

<div id="CategoryContent">
     <h2 id="errorMessage">No results found, Please reset filter and search again</h2>

    <div class="product">Brand1</div>
    <div class="product">Brand2</div>
    <div class="product">Brand3</div>
    <div class="product">Brand4</div>
    <br>
    <br>
    <br>
    <br>
    <br>
     <h2>Brands:</h2>

    <input type="checkbox" name="brand" value="Brand1" />Brand1</br>
    <input type="checkbox" name="brand" value="Brand2" />Brand2</br>
    <input type="checkbox" name="brand" value="Brand3" />Brand3</br>
    <input type="checkbox" name="brand" value="Brand4" />Brand4</br>
</div>

jQuery

var $filters = $("input:checkbox[name='brand']").prop('checked', true), // start all checked
    $categoryContent = $('#CategoryContent div'),
    $errorMessage = $('#errorMessage');

$filters.click(function () {
    // if any of the checkboxes for brand are checked, you want to show div's containing their value, and you want to hide all the rest.
    $categoryContent.hide();
    var $selectedFilters = $filters.filter(':checked');
    if ($selectedFilters.length > 0) {
        $errorMessage.hide();
        $selectedFilters.each(function (i, el) {
            $categoryContent.filter(':contains(' + el.value + ')').show();
        });
    } else {
        $errorMessage.show();
    }

});

CSS

#CategoryContent {
    width:920px;
    margin:auto;
}
.product {
    width:50px;
    height:50px;
    display:block;
    margin-bottom:10px;
    margin-right:10px;
    background:red;
    float:left;
}
#errorMessage {
    display: none;
}
于 2013-05-13T07:25:39.600 に答える