表單元件是網頁互動中常見的資料輸入方式。透過 DOM,我們可以讀取使用者選擇、設定預設值,也能批次處理多個表單項目。
單選按鈕通常由相同 name 的多個 input type="radio" 組成,同一時間只能有一個項目被選中。每個單選按鈕都有 checked 屬性,可用來判斷是否被選取。
var oForm = document.forms["uForm1"];
var aChoices = oForm.camera;
for (var i = 0; i < aChoices.length; i++) {
if (aChoices[i].checked) break;
}
alert("目前選擇:" + aChoices[i].value);若要程式化設定某一個選項,可直接將該元素的 checked 設為 true。
複選框允許使用者同時選擇多個項目。操作時通常會遍歷所有同群組的 checkbox,收集已勾選的值。
var boxes = document.getElementsByName("hobby");
var selected = [];
for (var i = 0; i < boxes.length; i++) {
if (boxes[i].checked) selected.push(boxes[i].value);
}
alert(selected.join(","));下拉選單由 select 與多個 option 組成。常用屬性包含 length、selectedIndex、options、text、value 與 type。單選時可透過 selectedIndex 取得目前選項。
var oSelectBox = document.forms["myForm1"].constellation;
var iChoice = oSelectBox.selectedIndex;
alert("您選中了:" + oSelectBox.options[iChoice].text);若為多選下拉選單,則需要遍歷 options,收集所有 selected 為真的項目。