<input type="text" name="test" id="test">
// 取值
var t = document.getElementById("test").value;
// 設值
var m = "5";
document.getElementById("test").value = m;
<select name="sel" id="sel" onchange="look();">
<option value="1">11</option>
<option value="2" selected>22</option>
<option value="3">33</option>
</select>
var s = document.getElementById("sel").value; // "2"(取 value,非顯示文字)
function look() {
var se = document.getElementById("sel");
var options = se.getElementsByTagName("option");
for (var i = 0; i < options.length; i++) {
if (options[i].selected) {
document.getElementById("test").value = options[i].text; // 取文字 "22"
}
}
}
var m = "2";
for (var i = 0; i < document.getElementById("sel").length; i++) {
with (document.getElementById("sel").options[i]) {
if (value == m) selected = true;
}
}
| 需求 | IE & Firefox 通用 | 僅 IE |
|---|---|---|
| 取得選中文字 | obj.options[obj.selectedIndex].text 或迴圈 obj[i].text | obj[i].innerText |
| 取得選中值 | obj.value 或 obj.options[obj.selectedIndex].value | 同上 |
結論: 統一使用 .value 與 .text,避免 innerText 相容性問題。
同群組 name 必須相同:
<input type="radio" name="a" value="1">aaaaaaaaaa<br>
<input type="radio" name="a" value="2">bbbbbbbbb<br>
<input type="button" onclick="check();" value="test">
function check() {
var sel = 0;
var radios = document.getElementsByName("a");
for (var i = 0; i < radios.length; i++) {
if (radios[i].checked) {
sel = radios[i].value;
}
}
if (sel == 1) alert("aaaaaaaaaa");
else if (sel == 2) alert("bbbbbbbbb");
}
// 文字框
const val = document.querySelector('#test').value;
// 下拉選單
const selVal = document.querySelector('#sel').value;
const selText = document.querySelector('#sel').selectedOptions[0].text;
// 單選按鈕
const radioVal = document.querySelector('input[name="a"]:checked')?.value;