방법 - 테이블 필터링/검색
JavaScript로 필터 테이블을 만드는 방법을 알아보세요.
필터 테이블
JavaScript를 사용하여 테이블에서 특정 데이터를 검색하는 방법.
이름 | 국가 |
---|---|
알프레드의 먹이통 | 독일 |
Berglund의 빠른 컵 | 스웨덴 |
섬 무역 | 영국 |
왕실 음식 | 독일 |
웃는 박카스 포도주 저장고 | 캐나다 |
수집 식품 창고 | 이탈리아 |
북쪽/남쪽 | 영국 |
파리 특산품 | 프랑스 |
필터링된 테이블 생성
1단계) HTML 추가:
예시
<input type="text" id="myInput" onkeyup="myFunction()" placeholder="Search
for names..">
<table id="myTable">
<tr class="header">
<th style="width:60%;">Name</th>
<th
style="width:40%;">Country</th>
</tr>
<tr>
<td>Alfreds Futterkiste</td>
<td>Germany</td>
</tr>
<tr>
<td>Berglunds snabbkop</td>
<td>Sweden</td>
</tr>
<tr>
<td>Island Trading</td>
<td>UK</td>
</tr>
<tr>
<td>Koniglich Essen</td>
<td>Germany</td>
</tr>
</table>
2단계) CSS 추가:
입력 요소와 테이블의 스타일 지정:
예시
#myInput {
background-image: url('/css/searchicon.png');
/* Add a search icon to input */
background-position:
10px 12px; /* Position the search icon */
background-repeat: no-repeat; /* Do not repeat the icon image */
width: 100%; /* Full-width */
font-size: 16px; /*
Increase font-size */
padding: 12px 20px 12px 40px; /*
Add some padding */
border: 1px solid #ddd; /* Add a
grey border */
margin-bottom: 12px; /* Add some space
below the input */
}
#myTable {
border-collapse: collapse; /* Collapse borders */
width: 100%; /* Full-width */
border: 1px solid #ddd;
/* Add a grey border */
font-size: 18px; /* Increase
font-size */
}
#myTable th, #myTable td {
text-align: left; /* Left-align text */
padding: 12px;
/* Add padding */
}
#myTable tr {
/* Add a bottom border to all table rows */
border-bottom: 1px solid #ddd;
}
#myTable tr.header, #myTable
tr:hover {
/* Add a grey background color to the table
header and on hover */
background-color: #f1f1f1;
}
3단계) 자바스크립트 추가:
예시
<script>
function myFunction() {
// Declare variables
var input, filter,
table, tr, td, i, txtValue;
input = document.getElementById("myInput");
filter = input.value.toUpperCase();
table =
document.getElementById("myTable");
tr =
table.getElementsByTagName("tr");
// Loop through all table
rows, and hide those who don't match the search query
for (i = 0; i < tr.length; i++)
{
td = tr[i].getElementsByTagName("td")[0];
if (td) {
txtValue = td.textContent ||
td.innerText;
if (txtValue.toUpperCase().indexOf(filter)
> -1) {
tr[i].style.display = "";
} else {
tr[i].style.display = "none";
}
}
}
}
</script>
팁: 대소문자를 구분하는 검색을 수행하려면 toUpperCase() 를 제거하십시오 .
팁: "이름"(인덱스 0) 대신 "국가"(인덱스 1)를 검색하려면 tr[i].getElementsByTagName('td') [0] 을 [1] 로 변경 하십시오.
팁: 필터 목록 도 확인하십시오 .