iT邦幫忙

2025 iThome 鐵人賽

DAY 16
0
自我挑戰組

打造一個糖尿病自我監測小工具:從0開始學前端系列 第 16

Day16打造一個糖尿病自我監測小工具:從0開始學前端

  • 分享至 

  • xImage
  •  

昨天說要加上刪除功能血糖圖表,想了想刪除功能應該在 record.html 不應該在 report.html ,所以刪除功能決定改成在填寫表單的最下面加入一個按鈕:清除所有資料,但這部分比較簡單,所以今天目標放在血糖圖表的部分。

刪除功能

  1. 在 record.html 的 Form表單最下面加上一顆 button 的清除按鈕。
<button type="button" id="clearBtn" style="background-color:#d9534f;">
  清除填寫資訊
</button>
  1. 加入功能 script.js :清除表單的功能
if (clearBtn) {
  clearBtn.addEventListener("click", function () {
    if (confirm("確定要清空表單內容嗎?")) {
      form.reset(); // 清掉所有表單輸入

      // 額外:把運動/藥物細節的顯示狀態重設
      handleRadioGroupChange(exerciseRadios, exerciseDetail);

      const checkedMed = document.querySelector('input[name="medication"]:checked');
      toggleMedicationDetail(checkedMed && checkedMed.value === "yes");

      alert("表單已清空!");
    }
  });
}

這樣就會在最下面看到地個紅色的按鈕,點擊後會刪除上面提好的資訊即可重新填表單。

成果呈現

https://ithelp.ithome.com.tw/upload/images/20250916/20169698at7Pt1R651.png
https://ithelp.ithome.com.tw/upload/images/20250916/20169698yOl9qxFJpf.png
https://ithelp.ithome.com.tw/upload/images/20250916/20169698vn7vWf93oz.png

血糖圖表

  1. 在HTML加上圖表容器

    <div style="width: 80%; margin: 20px auto;">
      <canvas id="glucoseChart"></canvas>
    </div>
    
  2. 引入Chart.js

    先來了解一下Chart.js :

    • 開源圖表套件
    • 只需要在 HTML 裡加上一個 <canvas> 加上一點JS → 就能畫圖
    • 能畫很多種圖
    • 會顯示數據 Tooltip,也支援動畫
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
  1. 在 JavaScript 裡加畫圖程式
const ctx = document.getElementById("glucoseChart").getContext("2d");

  const labels = records.map(r => r.date);
  const bfData = records.map(r => r.bf_glucose);
  const afData = records.map(r => r.af_glucose);

  new Chart(ctx, {
    type: "line",
    data: {
      labels: labels,
      datasets: [
        {
          label: "餐前血糖",
          data: bfData,
          borderColor: "blue",
          fill: false,
        },
        {
          label: "餐後血糖",
          data: afData,
          borderColor: "red",
          fill: false,
        },
      ],
    },
    options: {
      responsive: true,
      scales: {
        y: {
          title: {
            display: true,
            text: "血糖值 (mg/dL)"
          }
        },
        x: {
          title: {
            display: true,
            text: "日期"
          }
        }
      }
    }
  });
});
  • 先找出glucoseChart 在 HTML 的位子
  • 找到:標籤、餐前血糖值、餐後血糖值
  • 開始畫圖
    • 決定要何種圖表
    • 設定資料
    • 設定 XY 軸

成果呈現

https://ithelp.ithome.com.tw/upload/images/20250916/20169698z1bt5K7tpy.png


上一篇
Day15打造一個糖尿病自我監測小工具:從0開始學前端
下一篇
Day17打造一個糖尿病自我監測小工具:從0開始學前端
系列文
打造一個糖尿病自我監測小工具:從0開始學前端23
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言