2013-01-21 57 views
0

我想添加智能自動完成到我的項目中,當用戶在任何輸入中輸入一個單詞時,從他自己的字典中自動完成。Jquery:創建一個字典來自動完成所有輸入

主人字典是保存每一個字內置他曾經提交給服務器像(array_values($ _ POST))

我現在的JS

$('input.complete').live('keyup.autocomplete', function(){ 
     var hi=$(this).val().toUpperCase(); 
     var was=this; 
     $(this).autocomplete({ 
//PROBLEM Should i consider to change source from ajax/mysql to different source ? 
//since there gona be too many requests ?? 
      source: function(request, response) { 
        $.ajax({ url: '<?=base_url()?>ajax/ac', 
//PROBLEM how can i set term=word currently being edited..(start=' ',end=pointerpos) 
        data: { 'term': this.term }, 
        dataType: "json", 
        type: "POST", 
        success: function(data){ 
         if(data.length){ 
          //response(data); 
      //Commented out cause i dont wana display dropdown.. just typeahead. 
           if(data[0]['value'].substr(0,hi.length).toUpperCase()==hi){ 
           $(was).val(data[0]['value']); 
//currently working with single word inputs..once i get how to select only current word will edit these.. 
           was.selectionStart=hi.length; 
           was.selectionEnd=data[0]['value'].length; 
          } 
         } 
        } 
       }); 
      }, 
      select: function(event, ui){}, 
      minLength: 2, 
      delay: 500 
     }); 

就像你看到的,我有2個問題

問題

  1. 如何我可以選擇用戶正在輸入的當前單詞嗎?
  2. 這是達到我的目標的好方法,或者我應該考慮不同的插件
+0

[select2](http://ivaynberg.github.com/select2/)是一個很棒的選擇/自動完成插件,有很多配置選項。 – spas

回答

-1

您正在使用PHP語言。所以在我看來,你可以使用PHP來更容易地解決你的問題。假設你在get.php文件中有php函數get_word($摘錄)。所以,

<?php 
    get_word($_POST['excerpt']); 
    function get_word($excerpt) { 
      // Find exact word from database or array using given $excerpt 
      // and return complete word. 
      return $complete_word; 
    } 
?> 

而在你的jQuery(假設輸入字段。輸入),

$(document).ready(function() { 
    $('.input').live('keyup',function() { 
      var excerpt = $(this).val(); 
      $.post("get.php", {excerpt:excerpt}, function(data) { 
       // do anything with data. 
       $('.input').val(data); 
      }); 
    }); 
}) 

爲了得到更精確,你可以得到一堆匹配從get.php文件中的單詞,並顯示列表單詞被選中。

+0

需要js找出用戶當前輸入的單詞,以便php可以完成 – Zalaboza

+0

@MomenMElZalabany,我無法理解這個問題。假設輸入中的用戶類型爲「Ap」。所以,js代碼激活,並在變量摘錄中設置「Ap」。然後,它發送「Ap」到get.php頁面。 在get.php頁面上,函數get_word()接收到「Ap」,並檢查數據庫中類似於「Ap」的單詞。假設它創建了「Apple」。它將「Apple」作爲數據返回給js代碼。 然後再次使用js,可以使用$('。input).val(data);將數據(Apple)設置爲輸入字段。 – user1995997