如何建立Rails中的jQuery的用户界面自动完成 [英] How to set-up jquery-ui autocomplete in Rails

查看:249
本文介绍了如何建立Rails中的jQuery的用户界面自动完成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要就如何落实在我的Rails应用一个的jQuery的UI自动完成一些帮助。

我要自动完成添加到一个文本字段,用户可以在客户输入名称。由于可以有成百上千的客户,我需要'远程'拉建议的自动完成值,如,从表中(至少这是我的理解)。

我没能理解的要点是如何提供建议值来自动完成文本框。我已阅读了jQuery的UI文档,但我似乎在这个问题上有点密集。

那么,我真想要的是我如何能得到这个在Rails应用程序,未必是对JavaScript的是如何建立一个完整的描述成功的例子(这是jQuery的的UI团队已经为我做=) )。

例如,我怎么prepare为自动完成数据,以及如何连接自动完成功能的文本框。


解决方案

好吧,我从来没有回答我的问题上面,所以我最后不得不弄清楚自己。我想我应该张贴我想出了万一有任何其他人那里谁知道同样的事情的解决方案。

你应该知道的第一件事是,这是我使用javascript第一次的经验,而我刚开了Rails的窍门。因此,通过各种手段,随意编辑,评论任何地方,你觉得我已经错。对还是错,至少我知道,它的功能我想它的方式。

我想表明这一点的最好办法就是通过例子。所以下面的是我如何得到自动完成构件在我的应用程序工作。你可以继续前进,把下面code在您的应用程序,即使你不明白发生了什么,那么我们就可以去了怎么每个部分通过实例工作。在这之后,你应该对如何修改为您的使用或折射它的把握。



包含jQuery UI的在Rails应用程序。

下载副本jQuery UI的和地点的的jQuery-UI-1.8.2.custom.min.js 您的 /公/ JavaScript的目录中。另外,请确保您有jQuery的本身的副本,这也是在同一个文件夹中。

包括在你的 application.html.erb 文件中是这样的。
(你可以随你的便,只要它们符合命名文件)<的jQuery UI的文件和文件的jQuery / p>

 &LT;%= javascript_include_tag'jquery.min','的jQuery-UI-1.8.2.custom.min.js'%GT;

在您的jQuery UI的下载,你将有一个包含所有你的CSS数据的文件夹中。该名称会根据您选择的主题,比如我选择的主题是库比蒂诺。将包含你的CSS数据转换成 /公/样式表/ 整个文件夹。然后在您的application.html.erb这样的CSS文件。

 &LT;%= stylesheet_link_tag'库比提诺/ jQuery的-UI-1.8.2.custom'%GT;



示例AUTOCOMPLETE JAVASCRIPT

现在采取code以下块,并将其放置在你的的意见之一。您可以在任何视图中使用,但要意识到,我已经从字面上属于一个名为'links_controller控制器现有视图拍摄它,它是从一个'people_controller获取数据。希望你足够了解Rails的制定出你需要改变所以这对你的作品的。

- 开始code的大块 -

 &LT;脚本类型=文/ JavaScript的&GT;
    $(函数(){ //下面是这将是自动完成的文本字段的名称
    $('#select_origin')。自动完成({
 //这表明必须键入自动完成查找在比赛前charcters的最小长度。
            的minLength:2,
 //这是的auocomplete建议的来源。在这种情况下,从人的控制器,JSON格式名称的列表。
            来源:'&LT;%= people_path(:JSON)%GT;,
  //当您移动向上向下的建议名单,与键盘这将更新文本字段。在我们的情况下,它将反映您在这是person.given_name建议看到相同的值。
            重点:函数(事件,UI){
                $('#select_origin)VAL(ui.item.person.given_name)。
                返回false;
            },
 //一旦在下拉列表中选择一个值,请执行以下操作:
            选择:函数(事件,UI){
 //将person.given_name值放入称为select_origin文本字段...
                $('#select_origin)VAL(ui.item.person.given_name)。
 //并将person.id到名为link_origin_id隐藏的文本框。
        $('#link_origin_id)VAL(ui.item.person.id)。
                返回false;
            }
        })
 //下面的code是直接从jQuery的例子。它是什么格式的数据将显示在下拉列表框,可定制。
        。数据(自动完成)._ renderItem =功能(UL,项目){
            返回$(&LT;立GT;&LT; /李&gt;中)
                。数据(item.autocomplete项)
 //现在刚刚要显示在列表中person.given_name。
                .append(&所述a取代;+ item.person.given_name +&下; / A&gt;中)
                .appendTo(微升);
        };
    });
    &LT; / SCRIPT&GT;&LT; H1&gt;新建链接&LT; / H1&GT;&LT;%的form_for(@link)做| F | %GT;
  &所述;%= f.error_messages%GT;&LT;! - 将在窗体下面的文本字段时,名称并不重要。最重要的是,他们匹配上你的JavaScript的名字 - &GT;
  &所述p为H.;
        选择您要链接哪个人:其中; BR /&GT;
&LT;! - 这是将自动完成文本字段。这到底是怎么显示是用户看到,但数据不会去任何地方 - &GT;
        &LT;输入ID =select_origin/&GT;
&LT;! - 这是一个将根据谁选择上给予人ID隐藏的文本框。此值将被作为一个参数 - &GT;
      &LT;输入ID =link_origin_idNAME =链接[origin_id]类型=隐藏/&GT;
  &所述; / P&GT;
&LT;! - 音符结束 - &GT;
  &所述p为H.;
    &LT;%= f.label:rcvd_id%GT;&LT; BR /&GT;
    &所述;%= f.text_field:rcvd_id%GT;
  &所述; / P&GT;
  &所述p为H.;
    &LT;%= f.label:LINK_TYPE%GT;&LT; BR /&GT;
    &所述;%= f.text_field:LINK_TYPE%GT;
  &所述; / P&GT;
  &所述p为H.;
    &LT;%= f.label:总结%GT;&LT; BR /&GT;
    &LT;%= f.text_area:总结%GT;
  &所述; / P&GT;
  &所述p为H.;
    &LT;%= f.label:活跃%GT;&LT; BR /&GT;
    &LT;%= f.check_box:活跃%GT;
  &所述; / P&GT;
  &所述p为H.;
    &LT;%= f.submit'创建'%GT;
  &所述; / P&GT;
&LT;%结束%GT;

- code结束大块 -

好吧,现在来连接点。



提供的数据自动填充用作几点建议

让我们通过连接一些数据的自动完成文本框可以在下拉菜单显示的建议开始。我们将使用的格式是JSON,但如果你不熟悉它......我也不是=)不要担心。这是不够好,知道这是格式化文本,以便你的其他部分/其他应用程序可以使用它的方法。

选项​​:

文本字段将需要的自动完成的数据在 源'被指定。因为我们想送人民的名单和他们的ID来自动完成,我们就会把以下内容作为源。

 来源:'&LT;%= people_path(:JSON)%GT;'

铁轨上面的帮手将转化为一个字符串 /people.json 。你并不需要创建一个页面 /people.json 。你做什么需要做的是告诉people_controller,当它接收/人与以.json格式的要求做什么。把下面的内容people_controller:

 高清指数
#我会解释这部分在某一时刻。
  如果PARAMS [:长期]
    @people = Person.find的(:全部:条件=&GT; ['GIVEN_NAME样的?,#{PARAMS [:长期]}%​​])
  其他
    @people = Person.all
  结束  做的respond_to |格式|
    format.html#index.html.erb
#在这里你可以指定如何处理/people.json的要求
    format.json {渲染:JSON =&GT; @ people.to_json}
    结束
结束

现在我们都在@people人被送到自动完成文本框。这带来了非常下一个点。



中使用的自动完成建议的过滤数据的基础上,输入

如何自动完成文本框知道如何根据您键入的内容过滤结果?

分配给文本字段的自动完成构件将发送任何你输入到文本字段作为参数传递给你的源:。发送的参数为。所以,如果你要输入乔到文本框,我们会做以下几点:

  /people.json?term=joe

这就是为什么我们的控制器中的以下内容:

 #如果使用自动完成,它将发送一个参数'术语',让我们赶上了这里
    如果PARAMS [:长期]
#然后我们限制分配给@people,通过使用术语值作为滤波器的记录数。
      @people = Person.find的(:全部:条件=&GT; ['GIVEN_NAME样的?,#{PARAMS [:长期]}%​​])
#在我的例子,我还需要访问的所有记录,当我第一次渲染页面,所以正常使用我指定所有。这有什么好做的自动完成,只是显示你我是如何用它在我的处境。
    其他
      @people = Person.all
    结束

现在,我们已经限制了分配给@people基于什么键入到文本框自动完成的记录数,我们现在可以把它转换成JSON格式的自动完成建议。

 的respond_to做|格式|
      format.html#index.html.erb
      format.json {渲染:JSON =&GT; @ people.to_json}
    结束

现在,只需查看这应该解释如何联系的其它国家一道code的大块里面的评论。

在最后,你应该有你的页面上的一个文本框充当自动完成和一个隐藏字段,将在参数发送ID到控制器。



定制您自己的AUTOCOMPLETE

一旦你理解了上面的,你想修改您的使用,你应该知道,JSON从控制器返回的格式如下:

<$p$p><$c$c>[{\"person\":{\"id\":1,\"given_name\":\"joe\",\"middle_name\":\"smith\",\"family_name\":\"jones\",\"nationality\":\"australian\"}}]

从JSON字符串访问不同的值在JavaScript这种情况下的方式将是:

ui.item.person.name_of_some_attribute_such_as_given_name

pretty,简单。像很多Rails中访问一个ActiveRecord属性。

最后一个音符。我花了很多时间寻找一种不同的方式来提供隐藏的价值,因为我以为,这个功能已经内置到jQuery的小部件。然而,这种情况并非如此。它是在官方的jQuery例子发送一个不同的值,则选择作为一个参数,该方法是使用隐藏字段清楚地示出

好吧,我希望帮助别人。

戴尔

I need some help on how to implement a jquery-ui autocomplete in my Rails app.

I want to add autocompletion to a text field where the user can enter in a customer name. As there can be hundreds of customers, I will need to pull the suggested auto-completion values 'remotely', as in, from a table (at least this is what I understand).

The main point I am failing to understand is how to provide the suggested values to the autocompletion textbox. I have read the jquery-ui docs, but I seem to be a bit dense on this matter.

So what I am really after is an example of how I can get this to work in a Rails app, not necessarily a full description of how the javascript is built (that's what the jquery-ui team has done for me =) ).

For example, how do I prepare the data for the autocompletion, and how do I attach the autocompletion functionality to a textbox.

解决方案

Well I never got an answer to my question above so I ended up having to figure it out for myself. I thought I should post the solution I came up with in case there are any other guys out there who are wondering the same thing.

First thing you should know is that this is my first experience with javascript, and I am just getting the hang of Rails. So by all means, feel free to edit, comment anywhere you feel I have gone wrong with this. Right or wrong at least I know that it functions the way I wanted it to.

I think the best way to show this is by example. So the following is how I got the autocomplete widget to work in my app. You can go ahead and put the following code in your app even if you don't understand what is happening, then we can go over how each part is working by example. After this you should have a grasp on how to modify it for your use or refractor it.


INCLUDE JQUERY UI IN YOUR RAILS APP.

Download a copy of the jQuery UI and place jquery-ui-1.8.2.custom.min.js inside your /public/javascript directory. Also make sure you have a copy of jQuery itself and that this is also in the same folder.

Include the jQuery UI file and the jQuery file in your application.html.erb file like this.
(you can name the files as you please as long as they match)

<%= javascript_include_tag 'jquery.min', 'jquery-ui-1.8.2.custom.min.js' %>

In your download of jQuery UI, you will have a folder that contains all of your CSS data. The name will vary based on the theme you chose, for example I chose the theme 'cupertino'. Place the entire folder containing your CSS data into '/public/stylesheets/'. Then include the CSS file in your application.html.erb like this.

<%= stylesheet_link_tag 'cupertino/jquery-ui-1.8.2.custom' %>


EXAMPLE AUTOCOMPLETE JAVASCRIPT

Now take the following chunk of code and place it in one of your 'new' views. You can use this in any view, but realize that I have literally taken it from an existing view belonging to a controller called 'links_controller', and it is pulling data from a 'people_controller'. Hopefully you know enough about Rails to work out what you need to change so this works for you.

-- Begin big chunk of code --

    <script type="text/javascript">
    $(function() {

 // Below is the name of the textfield that will be autocomplete    
    $('#select_origin').autocomplete({
 // This shows the min length of charcters that must be typed before the autocomplete looks for a match.
            minLength: 2,
 // This is the source of the auocomplete suggestions. In this case a list of names from the people controller, in JSON format.
            source: '<%= people_path(:json) %>',
  // This updates the textfield when you move the updown the suggestions list, with your keyboard. In our case it will reflect the same value that you see in the suggestions which is the person.given_name.
            focus: function(event, ui) {
                $('#select_origin').val(ui.item.person.given_name);
                return false;
            },
 // Once a value in the drop down list is selected, do the following:
            select: function(event, ui) {
 // place the person.given_name value into the textfield called 'select_origin'...
                $('#select_origin').val(ui.item.person.given_name);
 // and place the person.id into the hidden textfield called 'link_origin_id'. 
        $('#link_origin_id').val(ui.item.person.id);
                return false;
            }
        })
 // The below code is straight from the jQuery example. It formats what data is displayed in the dropdown box, and can be customized.
        .data( "autocomplete" )._renderItem = function( ul, item ) {
            return $( "<li></li>" )
                .data( "item.autocomplete", item )
 // For now which just want to show the person.given_name in the list.
                .append( "<a>" + item.person.given_name + "</a>" )
                .appendTo( ul );
        };
    });
    </script>



<h1>New link</h1>

<% form_for(@link) do |f| %>
  <%= f.error_messages %>

<!-- Place the following text fields in your form, the names are not important. What is important is that they match the names in your javascript above -->
  <p>
        Select which person you want to link:<br /> 
<!-- This is the textfield that will autocomplete. What is displayed here is for the user to see but the data will not go anywhere -->
        <input id="select_origin"/>
<!-- This is the hidden textfield that will be given the Persons ID based on who is selected. This value will be sent as a parameter -->
      <input id="link_origin_id" name="link[origin_id]" type="hidden"/>
  </p>
<!-- end of notes -->
  <p>
    <%= f.label :rcvd_id %><br />
    <%= f.text_field :rcvd_id %>
  </p>
  <p>
    <%= f.label :link_type %><br />
    <%= f.text_field :link_type %>
  </p>
  <p>
    <%= f.label :summary %><br />
    <%= f.text_area :summary %>
  </p>
  <p>
    <%= f.label :active %><br />
    <%= f.check_box :active %>
  </p>
  <p>
    <%= f.submit 'Create' %>
  </p>
<% end %>

-- End Big Chunk of Code --

Okay now to connect the dots.


PROVIDE DATA FOR AUTOCOMPLETE TO USE AS SUGGESTIONS

Lets start by connecting up some data that the autocomplete textfield can display in the drop down suggestions. The format we will be using is JSON, but don't worry if you are not familiar with it ... neither am I =). It is good enough to know that it is a way to format text so that other parts of yours/other applications can use it.

The data the textfield will need for the autocomplete is specified in the 'source:' option. Because we want to send a list of peoples names and their ID to the autocomplete we will put the following as the source.

source: '<%= people_path(:json) %>'  

The rails helper above will translate to a string "/people.json". You do not need to create a page at "/people.json". What you do need to do is tell your people_controller what to do when it receives a request for /people with the .json format. Put the following into your people_controller:

def index  
# I will explain this part in a moment.
  if params[:term]
    @people = Person.find(:all,:conditions => ['given_name LIKE ?', "#{params[:term]}%"])
  else
    @people = Person.all
  end

  respond_to do |format|  
    format.html # index.html.erb  
# Here is where you can specify how to handle the request for "/people.json"
    format.json { render :json => @people.to_json }
    end
end

Now we have all the people in @people being sent to the autocomplete textfield. This brings up the very next point.


FILTER DATA USED FOR AUTOCOMPLETE SUGGESTION, BASED ON INPUT

How does the autocomplete textfield know how to filter the results based on what you type?

The autocomplete widget assigned to the textfield will send whatever you type into the textfield as a parameter to your source:. The parameter being sent is "term". So if you were to type "Joe" into the textfield, we would be doing the following:

/people.json?term=joe

That is why we have the following in the controller:

# If the autocomplete is used, it will send a parameter 'term', so we catch that here
    if params[:term]
# Then we limit the number of records assigned to @people, by using the term value as a filter.
      @people = Person.find(:all,:conditions => ['given_name LIKE ?', "#{params[:term]}%"])
# In my example, I still need to access all records when I first render the page, so for normal use I assign all. This has nothing to do with the autocomplete, just showing you how I used it in my situation.
    else
      @people = Person.all
    end

Now that we have limited the number of records assigned to @people based on what is typed into the autocomplete textfield, we can now turn that into JSON format for the autocomplete suggestions.

respond_to do |format|  
      format.html # index.html.erb  
      format.json { render :json => @people.to_json }
    end 

Now, just review the comments inside the "Big Chunk of Code" which should explain the rest of how this ties together.

At the end you should have a textfield on your page that acts as the autocomplete and a hidden field that will send the ID in a parameter to your controller.


CUSTOMIZE YOUR OWN AUTOCOMPLETE

Once you understand the above and you want to modify it for your use, you should know that the format JSON returned from your controller looks like this:

[{"person":{"id":1,"given_name":"joe","middle_name":"smith","family_name":"jones","nationality":"australian"}}]

The way to access the different values from the JSON string in your javascript in this case would be:

ui.item.person.name_of_some_attribute_such_as_given_name

Pretty, simple. A lot like accessing an ActiveRecord attribute in Rails.

One last note. I spent a lot of time looking for a different way to supply the hidden value, as I thought this function should have been built into the jquery widget. However, this is not the case. It is clearly shown in the official jQuery example that the way to send a different value then selected as a parameter, is to use a hidden field.

Well I hope that helps somebody.

Dale

这篇关于如何建立Rails中的jQuery的用户界面自动完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆