Technorati 的標籤:Jquery
最近寫到一個功能,為了要讓使用者快速建立表單,多半會有自動完成的功能,類似Google搜尋會跑出建議的選項點選
所以在Email欄位,希望能讓使用者Key的時候自動帶入常用的Host
網路上有Jquey Autocomplete 的套件,還沒深入研究過,但我想功能應該更齊全,
此範例只用官方的Jquery UI來完成:
首先先到官方網站下載頁面,第一個下拉選單可以選擇主題,其實只是載入不同的css檔
以下是下載後的檔案結構,我新增一個autocomplete的網頁檔
當然記得在<head></head>裡載入Jquery的 Js檔
在Body新增一個Input標籤
接著在<head></head>加入以下程式碼,
大概邏輯是每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>
最後的完成圖:
若文章有侵權地方,麻煩請告知,將迅速處理,謝謝!
沒有留言:
張貼留言