2009-05-11 5 views
4

jQuery를 사용하여 여러 줄 선택 상자를 필터링하는 방법이 있습니까?jQuery 필터링

저는 jQuery를 처음 사용 했으므로이 작업을 수행하는 가장 좋은 방법을 찾지 못했습니다. 예를 들어

내가있는 경우 :

<select size="10"> 
    <option>abc</option> 
    <option>acb</option> 
    <option>a</option> 
    <option>bca</option> 
    <option>bac</option> 
    <option>cab</option> 
    <option>cba</option> 
    ... 
</select> 

내가 함께 드롭 다운 선택에 따라이 목록을 필터링 할 : 트릭을 할 수있는이 같은

<select> 
    <option value="a">Filter by a</option> 
    <option value="b">Filter by b</option> 
    <option value="c">Filter by c</option> 
</select> 

답변

5

뭔가 (당신이 줄 가정하여 '필터링 기준'... 의 ID를 선택하고의 필터링 된/다른 ID는 otherOptions을 선택하십시오.

$(document).ready(function() { 
    $('#filter').change(function() { 
     var selectedFilter = $(this).val(); 
     $('#otherOptions option').show().each(function(i) { 
      var $currentOption = $(this); 
      if ($currentOption.val().indexOf(selectedFilter) !== 0) { 
       $currentOption.hide(); 
      } 
     }); 
    }); 
}); 

UPDATE : 없음을 : @ 브라이언 리앙이 의견에서 지적한 것처럼, 당신은 문제 디스플레이로 < 옵션 > 태그를 설정하지가있을 수 있습니다. 따라서 다음과 같이 브라우저 간 솔루션을 개선해야합니다.

$(document).ready(function() { 
    var allOptions = {}; 

    $('#otherOptions option').each(function(i) { 
     var $currentOption = $(this); 
     allOptions[$currentOption.val()] = $currentOption.text(); 
    }); 

    $('#filter').change(function() { 
     // Reset the filtered select before applying the filter again 
     setOptions('#otherOptions', allOptions); 
     var selectedFilter = $(this).val(); 
     var filteredOptions = {}; 

     $('#otherOptions option').each(function(i) { 
      var $currentOption = $(this); 

      if ($currentOption.val().indexOf(selectedFilter) === 0) { 
       filteredOptions[$currentOption.val()] = $currentOption.text(); 
      } 
     }); 

     setOptions('#otherOptions', filteredOptions); 
    }); 

    function setOptions(selectId, filteredOptions) { 
     var $select = $(selectId); 
     $select.html(''); 

     var options = new Array(); 
     for (var i in filteredOptions) { 
      options.push('<option value="'); 
      options.push(i); 
      options.push('">'); 
      options.push(filteredOptions[i]); 
      options.push('</option>'); 
     } 

     $select.html(options.join('')); 
    } 

}); 
+0

해당 옵션 요소를 숨길 수 없기 때문에이 방법이 효과가 있다고 생각하지 않습니다. –

+1

@ Brian Liang 게시하기 전에 Firefox에서 빠른 테스트를 수행했는데 성공했습니다. 그러나 Opera, Safari, Chrome 및 Internet Explorer 8에서 확인한 바 있습니다. 브라우저에서 작동하지 않습니다. –

+0

+1, 나는 그 아이디어가 마음에 든다. –