需求很典型:使用者切換下拉選單時,先把既有的勾選狀態清空,再用 AJAX 向後端要一份「該模板對應的指標清單」,最後把清單裡出現的項目自動打勾(checked = true)。以下用一個完整範例走過整個流程。
<select name="makemodule" id="makemodule" style="width:130px" onchange="makemoduleSelected()"> <option value="1">1</option> </select>
// 模板下拉框發生變化時觸發此事件(onchange)
function makemoduleSelected(){
clearAll('property'); // 先清除所有既有勾選
var modtitlecode = $("#makemodule").val();
$.ajax({
url: 'indexStatisticsAction_getSelect.jsp',
data: { page: 'clientindexStatistics.jsp', method: 'get_subname_en', modtitlecode: modtitlecode },
success: function(result){
var results = result.split(","); // 回傳字串切成陣列
$(".indexStatistics").each(function(){
$(this).find("input").each(function(){
var tempVal = $(this).val();
for(var i = 0; i < results.length; i++){
if(tempVal == results[i]) $(this).attr("checked", true);
}
});
});
}
});
}
流程說明:函式先清空畫面上的勾選狀態,接著向 indexStatisticsAction_getSelect.jsp 發出請求;伺服器回傳一段以逗號分隔的字串,前端把它切成陣列,然後遍歷 <div class="indexStatistics"> 底下所有的 input,比對 value 若命中就打勾。
// 取得模板對應的指標
if(method.equals("get_subname_en")){
String modtitlecode = request.getParameter("modtitlecode");
if(modtitlecode.equals("-------")) return;
String sql = sql2.replace("?modtitlecode?", modtitlecode);
sql = sql.replace("?userId?", userId);
System.out.println(sql);
StringBuffer subnames = new StringBuffer();
Db db = new Db();
try {
db.prepareQuery();
ResultSet rs = db.executeQuery(sql);
while (rs != null && rs.next()) {
subnames.append(rs.getString("subname_en"));
subnames.append(",");
}
rs.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
db.endQuery();
}
PrintWriter pout = response.getWriter();
pout.write(subnames.toString().substring(0, subnames.length() - 1));
pout.flush();
pout.close();
}
後端把查到的 subname_en 逐筆串接成逗號分隔字串,輸出前用 substring 去掉最後多餘的逗號,前端就能安全地 split(",")。
這個寫法以「value 比對」為基礎,因此核取方塊的 value 必須與後端回傳的英文代碼完全一致;另外,若表格項目數量很大,改用一次性的批次 selector 会比巢狀 each 迴圈更省資源。