Jquery autocomplete

白馬酒涼發表於2013-09-18


官網
http://api.jqueryui.com/autocomplete/

1. Source屬性可以為Json物件,label為下拉選單選中後出現在textbox的值,value是下拉選單讓user選擇的值
[ { label: "Choice1", value: "value1" }, ... ]
通常我們會另加個id值來標誌每個選項
後臺

    public String GetLangSource()
	{
	    IEnumerable<Langeuage> langList = GetAllLangs.ToList();
	  // [ { label: "Choice1", value: "value1" }, ... ] 
	   string list = "[";
	   foreach (Language lang in langList)
	   {
	       list += "{\"label\":\"" + lang.Name + "\",\"value\":\"" + lang.Name + "\",\"id\":\"" + lang.Id.ToString() + "\"},";
	   }
	    list += "]"; 
	    return list;
	} 


前臺

        $("#SelectLang").autocomplete({
            source: eval($('#LangSource').val()),
            mustMatch: true
            });

2.Source屬性也可以為一個http地址,使用get方法來每次實時獲取資料來源
後臺
     public JsonResult GetLangSource()
        {
        IEnumerable<Langeuage> langList = GetAllLangs.ToList();
            List<object> list = new List<object>();
            foreach (Language lang in langList)
            {
                var obj = new { label = lang.Name, value = lang.Name, id = lang.Id.ToString() };
                list.Add(obj);
            }
            return Json(list, JsonRequestBehavior.AllowGet);
        }   


前臺

          $("#SelectLang").autocomplete({
            source: '@Url.Action("GetLangSource")',
            mustMatch: true
            }); 

3.清空user隨便輸入非資料來源的字串
        $("#SelectLang").autocomplete({
            source: '@Url.Action("GetLangSource")',
            mustMatch: true,
            change: function (event, ui) {
                if ($.trim($(event.target).val()) == "") {
                    $("#SelectLangId").val(0);
                    return;
                }
            },
            select: function (event, ui) {
                $("#SelectLangId").val(ui.item.id);
            },
            response: function (event, ui) {
                if (ui.content.length == 0) {
                    $("#SelectLangId").val(0);
                    $(event.target).val("");
                    return;
                }
            }
        });












相關文章