【问题标题】:Jquery:create a dictionary to autocomplete all inputsJquery:创建一个字典来自动完成所有输入
【发布时间】:2013-01-21 10:13:36
【问题描述】:

我想在我的项目中添加一个智能自动完成功能,当用户在任何输入中输入一个单词时,它会从他自己的字典中自动完成。

他的所有者字典是通过将他曾经提交到服务器的每个单词保存到服务器来构建的,例如 (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. 这是实现我的目标的好方法,还是我应该考虑不同的插件

【问题讨论】:

  • select2 是一个很棒的选择/自动完成插件,有很多配置选项。

标签: php javascript jquery jquery-ui jquery-autocomplete


【解决方案1】:

您也在使用 PHP 语言。所以在我看来,您可以使用 PHP 更轻松地解决您的问题。假设您在 get.php 文件中有 php 函数 get_word($excerpt) 。所以,

<?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 中(假设输入字段为 .input),

$(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文件中得到一堆匹配的单词,并显示要选择的单词列表。

【讨论】:

  • 需要js找出用户当前输入的单词以便php完成
  • @MomenMElZalabany,我无法理解这个问题。假设用户在输入中键入“Ap”。因此,js 代码激活,并在变量摘录中设置“Ap”。然后,它发送“Ap”到get.php 页面。在 get.php 页面上,函数 get_word() 接收“Ap”,并检查数据库中与“Ap”相似的单词。假设它创建了“Apple”。它将“Apple”作为数据返回给 js 代码。然后再次使用js,数据(Apple)可以设置为输入字段使用,$('.input).val(data);
猜你喜欢
  • 2011-02-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-01-25
  • 1970-01-01
  • 2011-11-16
相关资源
最近更新 更多