JS動態建立combobox

來源:互聯網
上載者:User

JS動態建立combobox

在平時的學習過程中沒有怎麼寫過JS代碼,因為不熟悉,所以多多少少對JS代碼有一種恐懼。到了公司,鋪天蓋地的JS代碼,簡直讓人哭笑不得。在這漫天都是JS代碼的世界裡,我也慢慢的見識了些許,以一個小功能先來熱熱身:

 

使用JS代碼動態建立combobox,功能很簡單就是使用ajax非同步從後台擷取資料,然後在前台顯示就可是了,那麼具體的JS代碼如何寫呢?背景代碼又如何寫呢?

 

Js:

 

$dialog.find("select[name=materialunitid]").change(function() {if ($(this).val()) {$dialog.find("select[name=productid]").removeAttr("disabled");$.ajax({url: contextPath + "/jobcontent/getproductsbyunitid.do?unitid=" + $(this).val() + "&t=" + $.now(),async: false,dataType: "json",success: function(data) {var $select = $dialog.find("select[name=productid]").empty();$select.append(new Option("Select...", ""));if (data && data.length) {$.each(data, function(i, t) {$select.append(new Option(t.productname, t.id));});}}});} }

 

使用find() 方法獲得當前元素集合中每個元素的後代,通過選取器、jQuery 對象或元素來篩選;使用ajax動態從後台擷取要顯示的資料;使用append方法動態添加Option。

 

Action:

 

@RequestMapping("/getproductsbyunitid.do")@ResponseBody@Overridepublic Object getProductsByUnitId(HttpServletRequest request) {String unitId = request.getParameter("unitid");List results = jobContentService.queryEntities(DataProducts.class, null, DataProducts.PROP_MATERIALUNITID+ " = '" + unitId + "'", null, null, null);if (results != null && results.size() > 0) {return JSONArray.fromObject(results).toString();}return "[]";}

 

使用HttpServletRequest從前台擷取Id;根據Id到後資料庫中去查詢資料;將資料轉換成JSON串傳遞到前台。

 

 

使用JS代碼控制下拉框不可編輯功能:

 

方法一:

 

$('#cc').combobox({    required:true,    multiple:true,disabled:true  }); 

 

方法二:

 

$('#cdeptno').combobox("disable");
動態擷取下拉框中被選中的值:
var unitname = $dialog.find("select[name=materialunitid] option:selected").text();
總結:

寫JS代碼其實和寫背景代碼沒有什麼太大的區別,理清思路,按照你的思路去寫,多注意特定的擷取方式就可以了。

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.