2011-05-10 2 views
2

사용자가 여러 select 요소에서 선택한 항목을 기반으로 jQuery hide/show를 사용하여 테이블을 필터링하려고합니다.jQuery를 사용하여 여러 select 요소에서 테이블 필터링

사용자가 select 요소 중 1, 2 또는 3에서 여러 값을 선택할 수있게하려고합니다. 어쩌면 그들은 2 명의 강사, 1 명의 채용 및 1 개의 지위, 또는 단지 1 명의 강사를 선택할 것입니다. 사용자가 옵션을 클릭 할 때 실행되는 함수 작성 계획.

내가 보는 방식대로 각 선택 요소에는 사용자가 선택한 값 배열이 있습니다. 그래서 각 배열을 반복하여 특정 열의 텍스트와 비교해야합니다. 옵션이 단지 1 개의 select 요소에서 나온다면 충분히 쉬울 것입니다. 하지만 1, 2, 3 모두가 될 수 있기 때문에 머리를 감싸는 데 어려움을 겪고 있습니다.

어떤 도움을 주시면 감사하겠습니다.

테이블 :

<table id="reportsTable"> 
    <thead> 
    <th>Report Number</th> 
    <th>Date</th> 
    <th>Name</th> 
    <th>Trainer</th> 
    <th>Status</th> 
    </thead> 
    <tbody> 
    <tr> 
     <td>12345-1</td> 
     <td>05/01/2011</td> 
     <td>First Recruit</td> 
     <td>First Trainer</td> 
     <td>Complete</td> 
    </tr> 
    <tr> 
     <td>12345-2</td> 
     <td>05/02/2011</td> 
     <td>First Recruit</td> 
     <td>Second Trainer</td> 
     <td>In Progress</td> 
    </tr> 
    <tr> 
     <td>54321-1</td> 
     <td>05/03/2011</td> 
     <td>Second Recruit</td> 
     <td>First Trainer</td> 
     <td>Created</td> 
    </tr> 
    </tbody> 
</table> 

선택 : 나는 8 시간 동안 내 질문에 대한 답변을 게시 할 수 없습니다하지만이처럼

<select multiple="multiple" name="trainerFilter"> 
    <option value="firsttrainer">First Trainer</option> 
    <option value="secondtrainer">Second Trainer</option> 
</select> 
<select multiple="multiple" name="recruitFilter"> 
    <option value="firstrecruit">First Recruit</option> 
    <option value="secondrecruit">Second Recruit</option> 
</select> 
<select multiple="multiple" name="statusFilter"> 
    <option value="created">Created</option> 
    <option value="inprogress">In Progress</option> 
    <option value="complete">Complete</option> 
</select> 

내가 @Spencer하는 Ruport 덕분에 해낸 보이는 . 모든 가능한 항목을 설명해야하는 덕분에 예상보다 훨씬 복잡하게되었습니다. 사용자는 첫 번째 select 요소에서 무언가를 선택할 수 있고, 두 번째 요소는 선택하지 않을 수도 있고, 세 번째 요소에서 2를 선택할 수도 있습니다. 아니면 사용자가 처음부터 아무것도 선택하지 않고 두 번째에서 2를 선택하지 않을 수도 있습니다. 주어진 입력에 대해 적용 할 필요가있는 것보다 6 개 이상의 필터가있을 수 있습니다.

이보다 더 좋은 방법이있을 것이라고 생각합니다. @Alison이 연결되어있는 것처럼 보이지만 작동합니다.

function filterReports() { 
     $('.report').hide(); //Set all rows to hidden. 
     trainerVals = $('#trainerFilter').val(); 
     recruitVals = $('#recruitFilter').val(); 
     statusVals = $('#statusFilter').val(); 
     if (trainerVals) { //Check if any trainers are selected. 
      $.each(trainerVals, function(index, trainer) { 
       filtered = false; 
       classString = ''; 
       classString += '.' + trainer; 
       if (recruitVals) { //Check if trainers and recruits are selected. 
        $.each(recruitVals, function(index, recruit) { 
         filtered = false; 
         secondString = ''; 
         secondString = classString + '.' + recruit; //Concat to a new string so we keep the old one intact. 
         if (statusVals) { //Check if trainers, recruits and statuses are selected. 
          $.each(statusVals, function(index, status) { 
           filtered = false; 
           finalString = ''; 
           finalString += secondString + '.' + status; //Again concat to a new string. 
           $(finalString).show(); 
           filtered = true; //By setting filtered to true, we only run the show once. 
          }); 
         } 
         if (!filtered) { //If trainers and recruits are selected, but not a status, we need to apply that filter. 
          $(secondString).show(); 
          filtered = true; 
         } 
        }); 
       } 
       if (!filtered && statusVals) { //If only trainers and statuses are selected, go through those. 
        $.each(statusVals, function(index, status) { 
         filtered = false; 
         finalString = ''; 
         finalString += classString + '.' + status; 
         $(finalString).show(); 
         filtered = true; 
        }); 
       } 
       if (!filtered) { //If only trainers are selected, apply that filter. 
        $(classString).show(); 
        filtered = true; 
       } 
      }); 
     } 
     if (!filtered && recruitVals) { //If trainers are not selected, by recruits are, run through the recruits. 
      $.each(recruitVals, function(index, recruit) { 
       classString = ''; 
       classString += '.' + recruit; 
       if (statusVals) { //Check if recruits and statuses are selected 
        $.each(statusVals, function(index, status) { 
         finalString = ''; 
         finalString += classString + '.' + status; 
         $(finalString).show(); 
         filtered = true; 
        }); 
       } 
       if (!filtered) { //If only recruits are selected, apply that filter. 
        $(classString).show(); 
        filtered = true; 
       } 
      }); 
     } 
     if (!filtered && statusVals) { //If both trainers and recruits are not selected, but statuses are, run through those. 
      $.each(statusVals, function(index, status) { 
       classString = ''; 
       classString += '.' + status; 
       $(classString).show(); 
       filtered = true; 
      }); 
     } 
     if (!filtered) { 
      //No filters selected. 
     } 
     $("tr").removeClass("even"); //Remove current zebra striping. 
     $("tr:visible:even").addClass("even"); //Add zebra striping only for rows that are visible. 
    } 

답변

0

이 여러 클래스를 사용 할 매우 간단하다 (그들은 스타일을 사용하지 않을 때 나는 보통 그들에게 마커를 호출합니다.)

<table> 
    <thead> 
    <th>Report Number</th> 
    <th>Date</th> 
    <th>Name</th> 
    <th>Trainer</th> 
    <th>Status</th> 
    </thead> 
    <tbody> 
    <tr class="obj_first_recruit obj_first_trainer obj_complete obj_row_item"> 
     <td>12345-1</td> 
     <td>05/01/2011</td> 
     <td>First Recruit</td> 
     <td>First Trainer</td> 
     <td>Complete</td> 
    </tr> 
    <tr class="obj_first_recruit obj_second_trainer obj_in_progress obj_row_item"> 
     <td>12345-2</td> 
     <td>05/02/2011</td> 
     <td>First Recruit</td> 
     <td>Second Trainer</td> 
     <td>In Progress</td> 
    </tr> 
    <tr class="obj_second_recruit obj_first_trainer obj_created obj_row_item"> 
     <td>54321-1</td> 
     <td>05/03/2011</td> 
     <td>Second Recruit</td> 
     <td>First Trainer</td> 
     <td>Created</td> 
    </tr> 
    </tbody> 
</table> 

그리고 언제 당신은 그냥 모든을 연결 필터링 할 예 :

$(".obj_row_item").hide(); 
$(".obj_first_recruit.obj_second_trainer.obj_in_progress").show(); 

간단히하기 위해 드롭 다운 값을 마커 이름과 일치 시키면 문장이 좋아 보이도록 할 수 있습니다 e :

$("." + $("#dropdown1").val() + "." + $("#dropdown2").val() + "." + $("#dropdown3").val()).show(); 
+0

의 예를 확인해야합니다. 때때로 가장 간단한 대답이 가장 좋습니다. 각 select 요소에서 여러 옵션을 고려해야합니다. 거기에 3 $ .each 문을 사용하지 않고 쉽게 할 수 있습니까? –

+0

아. 선택을 사용했다는 것을 나는 눈치 채지 못했다. 모든 항목은 처음에는 숨겨져 있기 때문에 선택을 반복하고 각 조합을 연결하고 의미가있는 경우 각 항목에 대해 show를 호출하는 3 단계 루프를 작성합니다. 선택한 항목의 현재 반복을 포함하는 각 레벨에 대한 변수를 만든 다음 위에 쓴 연결선을 변경하여 val 대신 변수를 사용하십시오. –

+0

도움 주셔서 감사합니다!루프는 사용자 입력이 가능하기 때문에 더 복잡해졌습니다. 그들은 첫 번째 입력에서 한 쌍을 선택할 수 있으며, 두 번째 입력에서는 아무것도 표시하지 않고 세 번째 입력에서 일부만 선택할 수도 있습니다. 나는 내 질문을 내가 생각해 낸 것으로 편집했다. 나는 그것이 가장 효율적인 방법에 가깝다고 생각하지만 작동한다. 감사! –

1

jQuery Datatables plug-in을 살펴보십시오. HTML 테이블을 손쉽게 조작 할 수 있습니다. 몇 가지 간단한 설정 변경, 당신은 쉽게 당신이 찾고있는 무엇을 할 수 (등.)

심지어 그것에 대해 생각하지 않았다 filtering using select elements

관련 문제