iT邦幫忙

2025 iThome 鐵人賽

DAY 8
0
自我挑戰組

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

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

  • 分享至 

  • xImage
  •  

仔細看了一下現在的表單,決定做一些JavaScript的加入以及更改。

超基礎JS

和HTML連接

const button = document.getElementById("btn");
  • const:宣告一個 ( 名為button ) 的變數
  • document:代表整個HTML文件,提供的一個入口,能夠去找、改動網頁上的元素。
  • getElementById:在HTML中找到一個ID名為 ( btn ) 的元素

用JS賦予元素功能

button.addEventListener("click", function() {
  alert("Hello!");
});
  • addEventListener:當使用者的行為 ( 當"點擊”時 )
  • function:就執行後方的方程式

Form的JS實作

目標為:

  1. 運動內容的部分,如果是選有,才出現填寫運動項目的欄位,沒有的話就不會出現
  2. 藥物使用的部分也是,如果是選有,才出現填寫運動項目的欄位,沒有的話就不會出現
  3. 多選的部分,感覺有點多餘所以先刪掉

程式碼

document.addEventListener("DOMContentLoaded", function(){
    // 找元素(若不存在會回傳 null)
    const exerciseRadios = document.querySelectorAll('input[name="exercise"]');
    const exerciseDetail = document.getElementById("exercise_detail");

    const medRadios = document.querySelectorAll('input[name="medication"]');
    const medicationDetail = document.getElementById("medication_detail");

    // 安全檢查:如果欄位不存在就跳過,不會報錯
    function safeToggle(detailEl, shouldShow){
        if(!detailEl)return;
        if(shouldShow){
            detailEl.classList.remove("hidden");
            detailEl.disabled = false;  //啟用輸入
        }else{
            detailEl.classList.add("hidden")
            detailEl.value = "";        //清空(避免殘留)
            detailEl.disabled = true;   //禁用輸入,避免被送出
        }
    }

    // 處理 radio 群組變更:找到被選中的值
    function handleRadioGroupChange(radios, detailEl) {
        if (!radios || radios.length === 0) return;
        // 監聽每一個 radio 的 change 事件
        radios.forEach(radio => {
            radio.addEventListener("change", function () {
                const checked = document.querySelector(`input[name="${radio.name}"]:checked`);
                const value = checked ? checked.value : null;
                // 如果選 'yes' 就顯示
                safeToggle(detailEl, value === "yes");
            });
        });

        // 初始設定(載入頁面時根據當前選項決定顯示或隱藏)
        const initiallyChecked = document.querySelector(`input[name="${radios[0].name}"]:checked`);
        safeToggle(detailEl, initiallyChecked && initiallyChecked.value === "yes");
    }

    // 套用到運動跟藥物
    handleRadioGroupChange(exerciseRadios, exerciseDetail);
    handleRadioGroupChange(medRadios, medicationDetail);

});

結果呈現

  • 選擇「有」時,有彈性填寫的框框
    https://ithelp.ithome.com.tw/upload/images/20250908/20169698ByPW5hQrpt.png
  • 選擇「沒有」時,框框不會出現
    https://ithelp.ithome.com.tw/upload/images/20250908/2016969811sPgOGfXy.png

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

尚未有邦友留言

立即登入留言