Hướng dẫn tạo filter list với Javascript - Demo
RUN
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <style> * { box-sizing: border-box; } .container { width: 500px; margin: auto; } #myInput { background-position: 10px 12px; background-repeat: no-repeat; width: 100%; font-size: 16px; padding: 15px; border: 1px solid #ddd; margin-bottom: 12px; } #myUL { list-style-type: none; display: none; padding: 0; margin: 0; } #myUL li a { border: 1px solid #ddd; margin-top: -1px; background-color: #f6f6f6; padding: 12px; text-decoration: none; font-size: 18px; color: black; display: block } #myUL li a.header { background-color: #e2e2e2; cursor: default; } #myUL li a:hover:not(.header) { background-color: #eee; } </style> </head> <body> <div class="container"> <h2>Freetuts.net hướng dẫn tạo Filter List</h2> <input type="text" id="myInput" placeholder="Search for City.." title="Type in a name of City"> <ul id="myUL"> <li><a href="#">Athens</a></li> <li><a href="#">Amsterdam</a></li> <li><a href="#">Atlanta</a></li> <li><a href="#">Alaska</a></li> <li><a href="#">Barcelona</a></li> <li><a href="#">Bologna</a></li> <li><a href="#">Berlin</a></li> <li><a href="#">Bordeaux</a></li> <li><a href="#">Copenhagen</a></li> <li><a href="#">Cardiff</a></li> <li><a href="#">Caen</a></li> <li><a href="#">Cannes</a></li> </ul> </div> </body> <script> // lấy thẻ input var input = document.getElementById("myInput"); // định nghĩa hàm xử lý myFunction function myFunction() { var filter, ul, li, a, i; // lấy giá trị người dùng nhập filter = input.value.toUpperCase(); ul = document.getElementById("myUL"); li = ul.getElementsByTagName("li"); // Nếu filter không có giá trị thị ẩn phần kết quare\ if (!filter) { ul.style.display = "none"; }else{ // lặp qua tất cả các thẻ li chứa kết quả for (i = 0; i < li.length; i++) { // lấy thẻ a trong các thẻ li a = li[i].getElementsByTagName("a")[0]; // kiểm tra giá trị nhập có tôn tại trong nội dung thẻ a if (a.innerHTML.toUpperCase().indexOf(filter) > -1) { //nếu có hiển thị phàn tử ul và các thẻ li đó ul.style.display = "block"; li[i].style.display = ""; } else { // nếu không ẩn các thẻ li li[i].style.display = "none"; } } } } //gán sự kiện cho thẻ input input.addEventListener("keyup", myFunction); </script> </html>
PHÓNG TO