編輯表單時,需要把資料庫的值回填到 select 與 radio 上。很多人直覺地用 jQuery 在 ready 裡做,但這其實是最糟的一種做法。本文比較三種方案。
<form method="post" action="">
<input type="radio" name="visible" value="1" />顯示<br>
<input type="radio" name="visible" value="0" />隱藏<br>
<select name="orderBy" id="orderBy">
<option value="0">0</option>
<option value="1">1</option>
</select><br>
<input type="reset">
</form>
瀏覽器對重新載入的表單會保留部分狀態,但這行為不可靠、跨瀏覽器不一致,不能當成方案。
<script type="text/javascript">
$(function(){
// 注意:這樣設定的並不是「真正的預設值」
$("input[type=radio][name=visible]").each(function() {
if ($(this).val() == '${teacher.visible}') {
$(this).attr("checked", "checked");
}
});
$("#orderBy option").each(function() {
if ($(this).val() == '${teacher.orderBy}') {
$(this).attr("selected", "selected");
}
});
});
</script>
attr 用法本身也偏:jQuery 1.6 之後應使用 prop("checked", true),attr 操作的是初始屬性而非當前狀態。用 JSP 的 JSTL 條件判斷,讓 HTML 一送達就是正確狀態:
<input type="radio" name="visible" value="1"
<c:if test="${teacher.visible == 1}">checked="checked"</c:if> />顯示<br>
<input type="radio" name="visible" value="0"
<c:if test="${teacher.visible == 0}">checked="checked"</c:if> />隱藏<br>
<select name="orderBy" id="orderBy">
<option value="0" <c:if test="${teacher.orderBy == 0}">selected</c:if>>0</option>
<option value="1" <c:if test="${teacher.orderBy == 1}">selected</c:if>>1</option>
</select>
這樣做的好處:沒有閃爍、reset 行為正確、停用 JS 也能用、程式碼更少。
Spring MVC 的表單標籤庫一行就解決:
<form:radiobutton path="visible" value="1" label="顯示" />
<form:radiobutton path="visible" value="0" label="隱藏" />
<form:select path="orderBy">
<form:options items="${orderOptions}" />
</form:select>
Thymeleaf 更簡潔,只要加上 th:field:
<input type="radio" th:field="*{visible}" value="1">顯示
<select th:field="*{orderBy}">
<option th:each="o : ${orderOptions}"
th:value="${o.value}" th:text="${o.label}">
</select>
伺服器端輸出仍應是首選。只有以下情境才交給前端:
而這兩種情況也應該用 element.value = x 或 radio.checked = true 這類標準 DOM 屬性,而非 jQuery 的 attr。
EL 表達式中若值可能是 null,${teacher.visible == 1} 在部分容器下會出例外或全部為 false。較穩妥的寫法是先給預設值,或使用 empty 判斷:
<c:choose>
<c:when test="${empty teacher.visible}">...</c:when>
<c:otherwise>...</c:otherwise>
</c:choose>