iT邦幫忙

2021 iThome 鐵人賽

DAY 3
0
自我挑戰組

以網頁呈現資料視覺化系列 第 3

Day3 眾裡尋它千百度

  • Filter

在海量的數據中如果想要快速找到特定關鍵字的資料,我們需要filter這個很實用的功能,讓我們可以將目光放在篩選後的結果做進一步分析。這裡可以參考W3Schools的範例

  • Implement

首先我們在table.js中,將filter本體的功能拆成一個獨立的function,其中輸入的內容我們命名為filter此變數,而原本表格中的內容透過loop在指定的index欄位下去抓出每個cell的內容,便將此變數命名為txtValue,如範例中如果想要與大小寫無關可在兩個變數都加上toUpperCase()(或是toLowerCase())處理。然後再用indexOf看filter是否在txtValue裡面,如果沒有,則將這個row的display設為"none":

function filterTable(input, table, index) {
  // Declare variables
  let filter, tr, td, i, txtValue;
  filter = input.value;
  tr = table.getElementsByTagName("tr");
  // Loop through all table rows, and hide those who don't match the search query
  for (i = 1; i < tr.length; i++) {
    td = tr[i].getElementsByTagName("td")[index];
    if (td) {
      txtValue = td.textContent || td.innerText;
      if (txtValue.indexOf(filter) > -1) {
        tr[i].style.display = "";
      } else {
        tr[i].style.display = "none";
      }
    }
  }
}

接下來我們回到HTML中,在表格上方加入一個輸入,屬性中type設定為text,並增加placeholder為Search ...,這樣就會有提示使用者要輸入的用途,然後增加onkeyup屬性為輸入後執行的動作,我們會呼叫filterTable_data(),最後給個id叫filterInput_data,並用和表格同樣div的設定包起來,這樣對齊比較美觀:

<div class="table-responsive px-2">
  <input type="text" id="filterInput_data" onkeyup="filterTable_data()" placeholder="Search ..." class="form-control"/>
</div>

接下來再回到table.js,做輸入完成後的function,將輸入的內容和對應的table給到filter本體的function:

function filterTable_data() {
  let input = document.getElementById("filterInput_data");
  let table = document.getElementById("dataTable");
  filterTable(input, table, 0);
}

我們可以測試一下,承續昨天的小班教學的成績表,我們現在只要打上每個人的小名就會顯示個人成績:
https://ithelp.ithome.com.tw/upload/images/20210904/20141158wXwAMSs8Kb.jpg
至於如果我們想要讓每個欄位都能做filter,這就是另一個(天)故事了...


上一篇
Day2 今晚我想來點CSV
下一篇
Day4 Are you my destiny?
系列文
以網頁呈現資料視覺化30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言