2012-08-01 115 views
0

我正在使用以下代碼通過使用複選框來篩選我的結果。它顯示已在共同檢查的項目的結果:使用複選框篩選結果

$('input').change(function() { 

    var room_array = new Array(), 
     loc_array = new Array(); 
    $('.br').each(function() { 
     if ($(this).is(':checked')) { 
      room_array.push($(this).data('bedrooms')); 
     } 
    }); 
    $('.loc').each(function() { 
     if ($(this).is(':checked')) { 
      loc_array.push($(this).data('location')); 
     } 
    }); 
    //console.log(loc_array, room_array); 
    $('li').each(function() { 
     if ($.inArray($(this).data('location'), loc_array) > -1 && $.inArray($(this).data('bedrooms'), room_array) > -1) { 
      $(this).show(); 
     } else { 
      $(this).hide(); 
     } 
    }); 
}); 
<input data-bedrooms="1" class="br" type="checkbox">1 bedroom<br> 
<input data-bedrooms="2" class="br" type="checkbox">2 bedrooms<br> 
<input data-bedrooms="3" class="br" type="checkbox">3 bedrooms<br><br> 

<input data-location="london" class="loc" type="checkbox">london<br> 
<input data-location="new-york" class="loc" type="checkbox">new york<br> 
<input data-location="paris" class="loc" type="checkbox">paris<br><br>  

<ul> 
    <li data-bedrooms="1" data-location="paris">1 bedroom apartment paris</li> 
    <li data-bedrooms="1" data-location="paris">1 bedroom apartment</li> 
     <! -- similar combinations --> 
    <li data-bedrooms="2" data-location="new-york">2 bedroom apartment new yor</li> 
</ul> 

JSFiddle

的問題是,當僅選擇1型複選框,別結果爲複選框t顯示。

但是,我想只允許選擇一種類型,例如,臥室的數量或位置。我怎樣才能做到這一點?

+0

編號建議你改變你的代碼,以便對結果的數據存儲爲JavaScript,然後那意思就是HTML與簡單的功能,這將讓你輕鬆地過濾結果。 – Luka 2012-08-01 14:50:10

回答

2

更換

if ($.inArray($(this).data('location'), loc_array) > -1 && $.inArray($(this).data('bedrooms'), room_array) > -1) { 

隨着

if (($.inArray($(this).data('location'), loc_array) > -1 || !$('.loc:checked').length) && ($.inArray($(this).data('bedrooms'), room_array) > -1 || !$('.br:checked').length)) { 

當該組沒有選中複選框時接受任何組的值。

順便說一句,你的提琴有兩個條目

<li data-bedrooms="2" data-location="paris">2 bedroom apartment paris</li> 

我改變了他們的一個london作爲你的第一個例子建議。

jsFiddle

0

此行

if ($.inArray($(this).data('location'), loc_array) > -1 && $.inArray($(this).data('bedrooms'), room_array) > -1) 

應該

if ($.inArray($(this).data('location'), loc_array) > -1 || $.inArray($(this).data('bedrooms'), room_array) > -1) 
+0

這將導致顯示的條目過多:http://jsfiddle.net/YEtgM/16/。 – Zeta 2012-08-01 14:54:52

+0

怎麼這樣?你能舉出證明這一點的例子嗎? – malificent 2012-08-01 15:01:06

+2

檢查「1間臥室」和「巴黎」。它應該只有兩個「巴黎一居室公寓」的參賽作品,但它也顯示了倫敦和巴黎的一些「兩居室公寓」。 – Zeta 2012-08-01 15:04:22