今天要了解如何填寫完表單後送出,會出現在 report.html 頁面中。因為目前還沒打算加入後端,所以先用 LocalStorage 這個功能代替。
存取簡單
如何使用:
localStorage.setItem("key", value) → 存資料localStorage.getItem("key") → 取資料localStorage.removeItem("key") → 刪某一筆localStorage.clear() → 清空全部只能存字串
JSON.stringify() 轉成字串。JSON.parse() 轉回來。容量大概 5MB
report.html → 再把 LocalStorage 裡的資料讀出來顯示<!-- record.html(重點片段) -->
<!DOCTYPE html>
<html lang="zh-Hant">
<head>
<meta charset="utf-8">
<title>填寫紀錄</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<h1>填寫追蹤狀況</h1>
<!-- 注意:form 要有 id="recordForm" -->
<form id="recordForm">
<label for="date">日期:</label>
<input type="date" id="date" name="date" required>
<label for="weight">體重:</label>
<input type="number" id="weight" name="weight" step="0.1">
<!-- 運動(radio) -->
<label>運動狀況:</label>
<div class="form-group">
<input type="radio" id="exercise_yes" name="exercise" value="yes">
<label for="exercise_yes">有</label>
<input type="radio" id="exercise_no" name="exercise" value="no" checked>
<label for="exercise_no">沒有</label>
</div>
<input type="text" id="exercise_detail" placeholder="請填寫運動內容" class="hidden" disabled>
<!-- 藥物(radio) -->
<label>藥物使用:</label>
<div class="form-group">
<input type="radio" id="med_yes" name="medication" value="yes">
<label for="med_yes">有</label>
<input type="radio" id="med_no" name="medication" value="no" checked>
<label for="med_no">沒有</label>
</div>
<input type="text" id="medication_detail" placeholder="請填寫時間和藥物" class="hidden" disabled>
<label for="bf_glucose">餐前血糖:</label>
<input type="number" id="bf_glucose" name="bf_glucose" min="0">
<label for="af_glucose">餐後血糖:</label>
<input type="number" id="af_glucose" name="af_glucose" min="0">
<label for="remark">備註:</label>
<textarea id="remark" name="remark" rows="3"></textarea>
<button type="submit">送出</button>
</form>
<!-- 引入處理 record 的 js(放在 body 結尾) -->
<script src="script.js"></script>
</body>
</html>
比原本多了:
step="0.1":通常用在 <input type="number"> 裡,數字的最小增量,可輸入至小數第一位,沒有 step 的話,預設就是整數checked:預設被選取,如果 value 是 yes ,選項就會被打勾,反之不打勾class="hidden" disabled:一開始隱藏 + 禁用,等使用者選了「有運動」之後,再用 JavaScript 把它 顯示 + 啟用。script.js 加上 localStorage 的部分
parseFloat(...):將輸入字串轉成數值(如果不是數字會是 NaN)。localStorage.getItem(key) → JSON.parse:把存在 localStorage 的字串還原成 JS 陣列。localStorage.setItem(key, JSON.stringify(existing)):把新陣列轉字串存回去。window.location.href = "report.html":存好後跳到報表頁。引入 report.js
<!DOCTYPE html>
<html lang="zh-Hant">
<head>
<meta charset="utf-8">
<title>紀錄報表</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<h1>紀錄列表</h1>
<button id="clearAll">清空全部紀錄</button>
<table id="recordTable">
<thead>
<tr>
<th>日期</th><th>體重</th><th>運動</th><th>運動內容</th>
<th>藥物</th><th>藥物內容</th><th>餐前血糖</th><th>餐後血糖</th><th>備註</th><th>操作</th>
</tr>
</thead>
<tbody>
<!-- JS 會把紀錄渲染進來 -->
</tbody>
</table>
<script src="report.js"></script>
</body>
</html>
escapeHtml 避免 XSS 與顯示問題。data-index 存每筆資料在陣列的位置,刪除時直接修改陣列、存回 localStorage。clearAll 用 localStorage.removeItem(key) 清掉整個項目。明天就要進行到實作啦~