2012-02-26 3 views
0

헤더와 일부 행이있는 테이블이 있습니다. 각 행에는 자체 그룹이 있으며 때로는 이전 그룹 코드와 유사 할 수 있습니다.
또한 그룹 ID가 포함 된 드롭 다운 목록이 있습니다. 드롭 다운 목록의 현재 값과 동일한 행만 표시하려고합니다. 예를 들어
이 내 테이블 id="myTable"입니다 : enter image description herejQuery에서 테이블의 지정된 행을 제거하는 방법

이 내 드롭 다운 :

<select id="groups" name="groups"> 
    <option value="1">1</option> 
    <option value="2">2</option> 
    <option value="3">3</option> 
</select> 
나는 사용자가 드롭 다운의 현재 선택한 항목을 변경 2 층과 3 행을 제거해야

jQuery를 사용하여 어떻게 할 수 있습니까? 이 같은

답변

2

뭔가 :

$("#groups").change(function() { 
    var currentGroup = $(this).val(); 
    $("#myTable tr").each(function() { 
     if (this.rowIndex==0) return; // skip heading 
     if ($(this).children("td").eq(-1).text() == currentGroup) 
      $(this).show(); 
     else 
      $(this).hide(); 
    }); 
});​ 

데모 : http://jsfiddle.net/DBCcF/1/

당신은 세 번째 열에 특정 클래스에 세포를 제공함으로써 JS를 단순화 할 수 있지만 그때는 그렇게, 마크 업을 복잡하게 생각한다. 당신이 좋아 하는게 뭐든간에.

0
$("#groups").on("change", function() { 
    var rowNum = $(this).val(); 
    $("#myTable tr") 
     .show() 
     .each(function() { 
      var $this = $(this).find("td:nth-child(3)"); 
      if ($this.text() !== rowNum) { 
       $this.closest("tr").hide(); 
      } 
     }); 
});​ 

Demo.

이렇게하면 선택한 행의 모든 ​​세 번째 셀의 내용에 대해 선택한 요소의 값을 검사합니다. 일치하지 않으면 숨 깁니다.

0

이렇게하는 방법에는 여러 가지가 있습니다. 가장 쉬운 방법은 테이블에서 groupid를 찾는 방법이 필요하므로 테이블 구조를 약간 변경해야합니다. 당신이 nth-child(3) 또는 eq(-1) 같은 유연성이 기술을 사용할 필요가 없습니다 것이다 제외하고

<tr> 
    <td>1</td> 
    <td>Jack</td> 
    <td class='groupId'>1</td> 
</tr> 

그런 다음 당신은 다른 답변과 유사하여 자바 스크립트를 작성합니다 : 당신은이 같은 그룹 ID가 들어있는 셀에 클래스를 추가한다 무엇을 할 수 있는지 . 이것은 자바 스크립트를 변경하는 데 더 유연하게 만듭니다.

이 같은 끝낼 수 :

function hideRows(){ 
    // find selected value (get only the first as multi-selected is not required) 
    var selected = $('#groups option:selected')[0].value; 
    // walk through all cells that have the groupId class 
    $('#myTable td.groupId').each(function(){ 
     // get current cell 
     var currentCell = $(this); 
     // get the cells groupid 
     var groupid = currentCell.text(); 
     // determine if it the group id matches the selected value and hide/show 
     if(groupid !== selected){ 
      currentCell.parent().hide(); 
     } 
     else{ 
      currentCell.parent().show(); 
     } 
    }); 
} 
// wire-up select change event 
$('#groups').change(hideRows); 

을 올바른 열을 aquire하는 상기 기술 중 하나에 의지해야하는 테이블의 그룹 ID 세포를 분리 할 수있는 방법이 없다면.

JSFiddle - http://jsfiddle.net/GFzcp/5/

관련 문제