테이블에서 동적으로 데이터 검색해 테이블 조회(filter) 및 검색어 하이라이트(highlight)
Tag And Script
<div class="search-box" style="margin: 5px 0 ;">
<input type="text" id="searchInput" class="frm_input" placeholder="검색"/>
<button type="button" class="btn btn_search">검색</button>
<button type="button" class="btn btn_search_reset" style="display: none;">초기화</button>
<span class="search_count_info"></span>
</div>
<table class="ex-table table-search">
<caption class="sound_only">목록</caption>
<thead>
<tr>
<th scope="col" nowrap>No</th>
<th scope="col" nowrap>이름</th>
<th scope="col" nowrap>내용</th>
</tr>
</thead>
<tbody>
<tr>
<td class="no" nowrap>1</td>
<td>홍길동</td>
<td>홍길동 입니다.</td>
</tr>
<tr>
<td class="no" nowrap>2</td>
<td>김수철</td>
<td>김수철 입니다.</td>
</tr>
<tr>
<td class="no" nowrap>3</td>
<td>이나영</td>
<td>이나영 입니다.</td>
</tr>
<tr>
<td class="no" nowrap>4</td>
<td>곰탱이</td>
<td>곰탱이 입니다.</td>
</tr>
</tbody>
</table>
<script>
$(function(e){
$(document).on('click', '.btn_search', function(e){
var sValue = $.trim( $('#searchInput').val() );
if(sValue) {
$('table.table-search tbody tr').filter(function(e) {
$(this).find('td span.highlight').contents().unwrap(); // 기존 하이라이트 제거 (unwrap)
if(sValue) {
var regex = new RegExp("("+sValue+")", "gi");// 정규식 생성 (g: 전체, i: 대소문자 무시)
$(this).html($(this).html().replace(regex, '<span class="highlight" style="background-color:yellow;">$1</span>'));// 내용 치환 : 하이라이트
}
$(this).toggle($(this).text().indexOf(sValue) > -1);
});
visibleRowCount = 0;
$('table.table-search tbody tr:visible').each(function (index, tr_item) {
$(tr_item).find('td.no').html((index + 1));
visibleRowCount++;
});
$('.btn_search_reset').show();
$('.search_count_info').html(visibleRowCount+'건 조회');
}
});
$(document).on('click', '.btn_search_reset', function(e){
$('#searchInput').val('');
$('.search_count_info').html('');
$('table.table-search tbody tr').each(function (index, tr_item) {
$(tr_item).css('display', 'table-row');
$(tr_item).find('td span.highlight').contents().unwrap(); // 기존 하이라이트 제거 (unwrap)
$(tr_item).find('td.no').html((index + 1));
});
$(this).hide();
});
});
</script>