سؤال

I have page with several radio buttons and a list of list items (ul/li). When first comes to the page, the full list will show. Checking on the radio will narrow down the list.

I found some jquery code, and it worked fine. What I want and couldn't find/do (in addition to the current filtering) is to make the filtering start when the page is loaded (no click yet) so that if there's any pre-defined/pre-checked radio (as in the first radio below) the list will be the one already filtered - not the full list.

Thanks for your help! Here's the link on jsfiddle: http://jsfiddle.net/3NdHt/

<div class="tags">
<label><input type="radio" rel="apac" name="geo" checked /> APAC</label>
<label><input type="radio" rel="emea" name="geo" /> EMEA</label>
<label><input type="radio" rel="east" name="geo" /> US East</label>
<label><input type="radio" rel="west" name="geo" /> US West</label>
</div>
<br />

<ul class="results">
<li class="apac">APAC 1</li>
<li class="apac">APAC 1</li>      
<li class="emea">EMEA </li>
<li class="west east">WEST EAST 1</li>  
<li class="west">WEST 2</li>     
<li class="east">EAST</li>      
</ul>    

Jquery:

$(document).ready(function() {
$('div.tags').delegate('input[type=radio]', 'change', function() {
  var $lis = $('.results > li'),
  $checked = $('input:checked');
  if ($checked.length) {
    var selector = $checked.map(function (){
        return '.' + $(this).attr('rel');
    }).get().join('');
        $lis.hide().filter(selector).show();  
  } else {
    $lis.show();
}
});
});
هل كانت مفيدة؟

المحلول

Pull the function out of the delegated change event (BTW you should use .on() instead of .delegate()) and then just call it on document ready.

jsFiddle example

$('div.tags').delegate('input[type=radio]', 'change', update);
update(); // THIS CALLS THE FUNCTION ON DOC READY

function update() {
    var $lis = $('.results > li'),
        $checked = $('input:checked');
    if ($checked.length) {
        var selector = $checked.map(function () {
            return '.' + $(this).attr('rel');
        }).get().join('');

        $lis.hide().filter(selector).show();

    } else {
        $lis.show();
    }
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top