表單控制項的 readonly 與 disabled 屬性在 HTML 與 JavaScript 中的寫法不同,是新手常踩的坑。本文釐清差異並示範正確用法。
HTML vs JavaScript 寫法差異
| 屬性 | HTML 寫法 | JavaScript 寫法 | 注意事項 |
| readonly | readonly="readonly" 或 readonly | element.readOnly = true | JS 必須駝峰式 readOnly,大小寫敏感 |
| disabled | disabled="disabled" 或 disabled | element.disabled = true | JS 同樣為 disabled(全小寫) |
錯誤與正確示範
const input = document.getElementById('myInput');
// ❌ 錯誤:HTML 習慣帶入 JS
input.readonly = true; // 無效!屬性名錯誤
input.readOnly = "readonly"; // 無效!值應為布林
// ✅ 正確
input.readOnly = true; // 唯讀
input.disabled = true; // 停用
readonly vs disabled 關鍵差異
| 行為 | readonly | disabled |
| 使用者可編輯 | 否 | 否 |
| 表單提交時包含值 | 是 | 否(不會送出) |
| 可接收焦點 | 是 | 否 |
| 可被 Tab 鍵選取 | 是 | 否 |
| 樣式預設外觀 | 正常 | 灰色/半透明 |
| 後端可接收值 | 是 | 否(需額外處理) |
實務應用場景
場景 1:顯示不可修改的帳號/ID(需提交)
<input type="text" id="userId" name="userId" value="U12345" readonly>
<script>
// JS 動態設定
document.getElementById('userId').readOnly = true;
</script>
場景 2:暫時停用編輯(不提交)
<input type="text" id="tempField" name="tempField" disabled>
<script>
// 條件解除停用
if (user.hasPermission) {
document.getElementById('tempField').disabled = false;
}
</script>
場景 3:readonly 搭配 CSS 強化視覺提示
input[readonly] {
background-color: #f5f5f5;
border-color: #ddd;
cursor: not-allowed;
}
動態切換完整範例
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>readonly / disabled 切換示範</title>
</head>
<body>
<label>唯讀欄位(會提交):
<input type="text" id="readonlyInput" value="不可編輯但會提交">
</label><br><br>
<label>停用欄位(不提交):
<input type="text" id="disabledInput" value="不可編輯也不提交">
</label><br><br>
<button onclick="toggleReadOnly()">切換唯讀</button>
<button onclick="toggleDisabled()">切換停用</button>
<button onclick="submitForm()">模擬提交</button>
<script>
function toggleReadOnly() {
const el = document.getElementById('readonlyInput');
el.readOnly = !el.readOnly;
console.log('readonly:', el.readOnly);
}
function toggleDisabled() {
const el = document.getElementById('disabledInput');
el.disabled = !el.disabled;
console.log('disabled:', el.disabled);
}
function submitForm() {
const formData = new FormData();
formData.append('readonly', document.getElementById('readonlyInput').value);
formData.append('disabled', document.getElementById('disabledInput').value);
console.log('提交資料:', Object.fromEntries(formData));
}
</script>
</body>
</html>
總結
- JS 設定唯讀:
element.readOnly = true(駝峰式,大 O)
- JS 設定停用:
element.disabled = true(全小寫)
- 需提交資料用
readonly,完全禁用用 disabled
- 後端接收時注意
disabled 欄位不會出現在 $_POST/$_GET 中