仔細看了一下現在的表單,決定做一些JavaScript的加入以及更改。
const button = document.getElementById("btn");
const
:宣告一個 ( 名為button ) 的變數document
:代表整個HTML文件,提供的一個入口,能夠去找、改動網頁上的元素。getElementById
:在HTML中找到一個ID名為 ( btn ) 的元素button.addEventListener("click", function() {
alert("Hello!");
});
目標為:
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);
});