2014-12-28 193 views
0

當我在2個或多個複選框上選擇時,遇到與我的jQuery複選框選擇有關的問題。我對前端編程還是一個新的東西,請耐心等待。有多個選擇的jQuery複選框選擇

1)當我選擇的第一個複選框和一個額外的第二個複選框它給所有不包括第二選擇的選擇的:在一個複選框

選擇/取消的偉大工程,但是選擇多個選擇時的問題所在。

2)當我第一個複選框取消選擇第二個複選框仍然檢查它給我所有的選擇。

看來我必須選擇兩個盒子才能正確註冊並給我正確的過濾選擇。

代碼在這裏: JSFiddle

HTML

<div class="tags"> 
<label> 
    <input type="checkbox" rel="accounting" />Accounting</label> 
<label> 
    <input type="checkbox" rel="courier" />Courier</label> 
<label> 
    <input type="checkbox" rel="project-management" />Project Management</label> 
<label> 
    <input type="checkbox" rel="video-games" />Video Games</label> 
</div> 
<ul class="results"> 
<li class="accounting" style="list-style-type:none"><a href="http://cnn.com" style="text-decoration: none">Accounting</a></li> 
<li class="courier" style="list-style-type:none"><a href="http://cnn.com" style="text-decoration: none">Courier</a></li> 
<li class="project-management" style="list-style-type:none"><a href="http://cnn.com" style="text-decoration: none">Project Management</a></li> 
<li class="video-games" style="list-style-type:none"><a href="http://cnn.com" style="text-decoration: none">Video Games</a></li> 
</ul> 

jQuery的

$(document).ready(function() { 
$('div.tags').find('input:checkbox').live('click', function() { 
    if ($(this).prop("checked")) { 
     $('.results > li').toggle('show'); 
     $('div.tags').find('input:checked').each(function() { 
      $('.results > li.' + $(this).attr('rel')).toggle('show'); 
     }); 
    } else{ 
     $('.results > li').show(); 
    } 
}); 
}); 
+0

這是你以後http://jsfiddle.net/j08691/too8joj7/? – j08691

+0

幾乎,你可以改變它,如果沒有選擇任何東西,整個列表顯示出來而不是什麼?並選擇每個提出這些選擇等。 – Kincsem

+0

因此,像http://jsfiddle.net/j08691/L9rtnswm/? – j08691

回答

1

這似乎是你所需要的:

$('div.tags').find('input:checkbox').on('click', function() { 
    var vals = $('input:checkbox:checked').map(function() { 
     return $(this).attr('rel'); 
    }).get(); 
    $('li').hide().filter(function() { 
     return ($.inArray($(this).attr('class'), vals) > -1) 
    }).show() 
    if ($('input:checkbox:checked').length == 0) $('li').show() 
}); 

jsFiddle example