[javascript] TableSorter를 이용한 필터링 기능 구현하기

웹 개발에서 데이터 테이블을 표시하고 필터링하는 것은 매우 일반적입니다. jQuery 플러그인 중 하나인 TableSorter는 이러한 작업을 간단하게 처리할 수 있도록 도와줍니다. 이제 TableSorter를 사용하여 데이터 테이블의 필터링 기능을 구현하는 방법에 대해 알아보겠습니다.

TableSorter 설정

TableSorter를 사용하기 위해 먼저 해당 라이브러리를 웹 페이지에 추가해야 합니다. 다음은 CDN을 통해 TableSorter를 추가하는 예시입니다.

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.tablesorter/2.33.3/js/jquery.tablesorter.min.js"></script>

HTML 구조

다음으로 데이터 테이블을 나타내는 HTML 코드를 작성합니다. 각 열에는 필터링을 위해 필요한 클래스를 추가해야 합니다.

<table id="myTable" class="tablesorter">
  <thead>
    <tr>
      <th class="filter-select">이름</th>
      <th class="filter-select">나이</th>
      <th class="filter-select">도시</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>John</td>
      <td>25</td>
      <td>New York</td>
    </tr>
    <tr>
      <td>Jane</td>
      <td>30</td>
      <td>Los Angeles</td>
    </tr>
    <!-- 나머지 테이블 데이터 -->
  </tbody>
</table>

스크립트

마지막으로 JavaScript를 사용하여 TableSorter를 초기화하고 필터링 기능을 활성화합니다.

$(document).ready(function(){
  $("#myTable").tablesorter({
    theme: 'blue',
    widgets: ['zebra', 'filter'],
    widgetOptions: {
      filter_external: '.search',
      filter_reset: '.reset'
    }
  });
});

위의 예시 코드에서는 tablesorter 함수를 호출할 때 filter 위젯을 활성화하고, 테마를 설정하고, 필터링을 위한 클래스를 지정하였습니다.

결과

이제 데이터 테이블은 TableSorter의 도움으로 인터랙티브한 필터링이 가능한 상태가 되었습니다. 사용자는 각 열에 있는 필터를 사용하여 원하는 데이터를 쉽게 찾을 수 있을 것입니다.

TableSorter를 사용하여 데이터 테이블의 필터링 기능을 구현하는 방법에 대한 간단한 소개였습니다. 보다 많은 기능과 옵션을 이용하고자 한다면 TableSorter 공식 문서를 참고하시기 바랍니다.