iT邦幫忙

3

[Jquery]搭配Jquery UI讓表單Email欄位自動完成

Jquery 最近寫到一個功能,為了要讓使用者快速建立表單,
多半會有自動完成的功能,類似Google搜尋會跑出建議的選項點選
所以在Email欄位,希望能讓使用者Key的時候自動帶入常用的Host
網路上有Jquey Autocomplete 的套件,還沒深入研究過,但我想功能應該更齊全。
http://www.pengoworks.com/workshop/jquery/autocomplete.htm
此範例只用官方的Jquery UI來完成:
首先先到官方網站下載頁面,第一個下拉選單可以選擇主題,其實只是載入不同的css檔
http://jqueryui.com/autocomplete/

以下是下載後的檔案結構,我新增一個autocomplete的網頁檔

當然記得在裡載入Jquery的 Js檔

在Body新增一個Input標籤

接著在加入以下程式碼,
大概邏輯是每MailData是我建立常用Email的資料
在Key in的時候將字串"@host.com",插入最後面

$(document).ready(function () {
	var MailData = ["gmail.com", "hotmail.com", "msn.com", "yahoo.com", "yahoo.com.tw", "pchome.com.tw"];
	$("#email").autocomplete({
		autoFocus: true,
		source: function (request, response) {
			var KeyValue = request.term,
				index = KeyValue.indexOf("@"),
				Address = KeyValue,
				host = "",
				result = [];

			result.push(KeyValue);
			if (index > -1) {
				Address = KeyValue.slice(0, index);
				host = KeyValue.slice(index + 1);
			}
			if (Address) {
				var findedHosts = (host ? $.grep(MailData, function (value) {
					return value.indexOf(host) > -1;
				}) : MailData),
				findedResults = $.map(findedHosts, function (value) {
					return Address + "@" + value;
				});
				result = result.concat($.makeArray(findedResults));
			}
			response(result);
		}
	});
});
</script>

最後的完成圖:


圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 則留言

0
Pyan
iT邦研究生 5 級 ‧ 2020-06-11 15:46:01

這個好用

我要留言

立即登入留言