DIV CSS 佈局教程網

用 jQuery 自動勾選核取方塊的實作
編輯:JavaScript綜合知識     

本文示範如何透過 ajax 取得勾選項清單,再用 jQuery 自動把對應的核取方塊勾選起來(checked=true)。

觸發來源:下拉選單

<select name="makemodule" id="makemodule" style="width:130px"
  onchange="makemoduleSelected()">
  <option value="1">1</option>
</select>

前端處理函式

當下拉選單變動時觸發 makemoduleSelected(),先清空舊勾選,再透過 ajax 取得資料並比對勾選。

// 模板下拉選單變動時觸發此事件
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);
          }
        });
      });
    }
  });
}

此函式向後端發出請求,取得字串後拆成陣列,接著遍歷 <div class="indexStatistics"> 下的 input,遇到相符的值就打勾。

後端回傳資料

// 取得模板對應的指標
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);
  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();
}

整合前後端,就能在使用者切換模板時,自動把該模板已設定的指標核取方塊勾選起來,省去手動勾選的麻煩。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved