使用 Struts2 的 <s:radio> 標籤時常會遇到一個困擾:明明設定了默認選中項,但表單提交返回後,單選框卻無法保留先前選取的狀態,仍顯示為默認選項。
以 <s:radio name="user.sex" list="%{#{'1':'男','0':'女'}}" theme="simple"> 為例,要讓它默認選中某一項,有兩種方法:
方法一:透過 JS 設定
document.getElementsByName('user.sex')[0].checked = true;// 默認選中「男」
方法二:加上 value 屬性
<s:radio name="user.sex" list="%{#{'1':'男','0':'女'}}" value="1" theme="simple">
兩者的關鍵差異在於:透過 value 屬性設定默認項時,每次頁面刷新後都會回到該默認值;因此若希望資料提交後台後仍保留使用者先前的選擇,就不能用 value 屬性,而應改用方法一。值得一提的是,後台能否正確取得單選框的值,與 value 的設定無關。
<s:radio/> 會在頁面自動生成一組 radio,每個的 id 會自動附加數字,例如:
<input type="radio" name="file" id="upfile_file0" value="0"><label for="upfile_file0">否</label> <input type="radio" name="file" id="upfile_file1" checked="checked" value="1" class="filetype"><label for="upfile_file1">是</label>
由於 id 帶有數字不方便直接選取,可以改用 jQuery:為 <s:radio/> 加上 cssClass="filetype" 屬性,讓每個 radio 都帶上同一個 class,再透過該 class 綁定事件:
$(function(){
$(".filetype").change(function(){
var val = $("input[name='file']:checked").val();// 取得選中 radio 的值
if(val == '1'){
alert("是");
}else{
alert("否");
}
});
});
這樣一來,就能用 class 選擇器精準抓到整組單選框,並在切換時觸發對應的業務邏輯。