質問

実装する方法については、いくつかのヘルプが必要です jQuery-uiオートコンプリート 私のRailsアプリで。

ユーザーが顧客名を入力できるテキストフィールドにAutoCompletionを追加したいと思います。何百もの顧客がいる可能性があるため、テーブルからのように、提案された自動完了値を「リモート」に引く必要があります(少なくともこれは私が理解していることです)。

私が理解していない主なポイントは、AutoCompletion TextBoxに提案された値をどのように提供するかです。 jquery-uiドキュメントを読んだことがありますが、この問題については少し密度が高いようです。

だから私が本当にそれを望んでいるのは、これをRailsアプリで機能させる方法の例です。必ずしもJavaScriptの構築方法についての完全な説明ではありません(JQuery-UIチームが私のために行ったこと=))。

たとえば、自動補完のためにデータを準備するにはどうすればよいですか?また、自動完了機能をテキストボックスに添付するにはどうすればよいですか。

役に立ちましたか?

解決

さて、私は上記の私の質問に対する答えを得たことがないので、私は自分でそれを理解する必要がありました。同じことを疑問に思っている他の人がいる場合に備えて、私が思いついた解決策を投稿するべきだと思いました。

あなたが知っておくべき最初のことは、これがJavaScriptでの私の最初の経験であり、私はちょうどRailsのハングを得ているということです。したがって、どうしてもお気軽に編集して、私がこれで間違っていると思うところならどこでもコメントしてください。正しいか間違っているか、少なくとも私はそれが私が望んでいた方法で機能することを知っています。

これを示すための最良の方法は例です。したがって、以下は、アプリで動作するオートコンプリートウィジェットを入手した方法です。何が起こっているのかわからなくても、次のコードをアプリに配置することができます。その場合、各パーツがどのように機能しているかを模範にすることができます。この後、使用するために変更する方法を把握するか、屈折する必要があります。


RailsアプリにjQuery UIを含めてください。

のコピーをダウンロードします jquery ui そして場所 jquery-ui-1.8.2.custom.min.js あなたの内側 /public/javascript ディレクトリ。また、jQuery自体のコピーがあり、これも同じフォルダーにあることを確認してください。

jquery uiファイルとjqueryファイルをあなたに含める application.html.erb このようなファイル。
(一致する限り、ファイルに名前を付けることができます)

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

jQuery UIのダウンロードでは、すべてのCSSデータを含むフォルダーがあります。名前は、あなたが選んだテーマに基づいて異なります。たとえば、テーマを選択しました。クパチーノ'。 CSSデータを含むフォルダー全体を 'に配置します/public/styleSheets/'。次に、application.html.erbにCSSファイルをこのように含めます。

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


AutoComplete JavaScriptの例

次のコードの塊を取り、それをあなたのいずれかに置いてください新着'ビュー。これを任意のビューで使用できますが、「links_controller」と呼ばれるコントローラーに属する既存のビューから文字通りそれを取得したことを認識し、「people_controller」からデータを取得しています。うまくいけば、あなたがあなたが変更するために必要なものを解決するためにレールについて十分に知っているので、これはあなたのために働きます。

- コードの大部分を開始します -

    <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 %>

- コードの大部分を終了 -

さて、ドットを接続してください。


AutoCompleteのデータを提供して、提案として使用します

Autocomplete Textfieldがドロップダウン提案で表示できるデータを接続することから始めましょう。使用する形式はJSONですが、慣れていなくても心配しないでください... i =)。それがテキストをフォーマットする方法であることを知るのに十分であり、あなたの/他のアプリケーションの他の部分がそれを使用できるようにします。

テキストフィールドがオートコンプリートに必要なデータは、ソース:' オプション。人々の名前とそのIDのリストをオートコンプリートに送信したいので、以下をソースとして配置します。

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

上のRailsヘルパーは、文字列に変換されます」/people.json「。でページを作成する必要はありません」/people.json"。あなたがする必要があるのは、.json形式の人のリクエストを受け取ったときにanepeal_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

今、私たちは@peopleのすべての人々がオートコンプリートのテキストフィールドに送られています。これにより、次のポイントが表示されます。


入力に基づいて、オートコンプリートの提案に使用されるフィルターデータ

オートコンプリートテキストフィールドは、タイプを使用して結果をフィルタリングする方法をどのように知っていますか?

Textfieldに割り当てられたオートコンプリートウィジェットは、テキストフィールドに入力するものをすべてソースにパラメーターとして送信します。送信されるパラメーターは "期間"。したがって、もしあなたがテキストフィールドに「ジョー」と入力するなら、私たちは以下をやっています:

/people.json?term=joe

そのため、コントローラーに以下があります。

# 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

オートコンプリートテキストフィールドに入力されたものに基づいて @ペオプルに割り当てられたレコードの数が制限されたので、オートコンプリートの提案のためにそれをJSON形式に変えることができます。

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

次に、「コードの大きな塊」内のコメントを確認するだけで、これがどのように結びついているかを説明するはずです。

最後に、オートコンプリートとして機能するテキストフィールドと、パラメーターのIDをコントローラーに送信する隠されたフィールドを使用する必要があります。


独自のオートコンプリートをカスタマイズします

上記を理解し、使用のために変更したい場合は、コントローラーから返されたフォーマットJSONが次のように見えることを知っておく必要があります。

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

この場合、JavaScriptのJSON文字列から異なる値にアクセスする方法は次のとおりです。

ui.item.person.name_of_some_attribute_such_as_given_name

ものすごく単純。 RailsでActiverCord属性にアクセスすることによく似ています。

最後のメモ。この関数はjQueryウィジェットに組み込まれるべきだと思ったので、隠された価値を提供するための別の方法を探すのに多くの時間を費やしました。ただし、そうではありません。公式のjQueryの例では、パラメーターとして選択されたものとは異なる値を送信する方法は、非表示フィールドを使用することであることが明確に示されています。

まあそれが誰かを助けることを願っています。

デール

他のヒント

jQuery 1.9/1.10キーオートコンプリートを削除し、uiautocompleteを追加しました

.data("uiAutocomplete") instead of .data("autocomplete")

上記に変更した後、それは私のために働きました。

デールの答え かなりのチュートリアルです。注意すべきことの1つは、最初のクエリを使用すると、DataSourceは一致のみを返すことです。 始まり 入力する文字列で。単語のどこでも検索したい場合は、変更する必要があります。

@people = Person.find(:all,:conditions =>
    ['given_name LIKE ?', "#{params[:term]}%"])

@people = Person.find(:all,:conditions =>
    ['given_name LIKE ?', "%#{params[:term]}%"])

(追加を追加しました % クエリに)

私は基本的に以下のDaleのアドバイスに従いましたが、私のコントローラーとJSファイルはわずかに違いでした。

コンテキスト:私はユーザーが入力したDJの名前をオートコンプリートしようとしています - またNewb

DJSコントローラー

 class DjsController < ApplicationController
    def index
     if params[:term]
       @djs = Dj.is_dj.where('lower(name) LIKE ?', "%#{params[:term].downcase}%")
       respond_to do |format|  
          format.html
          format.json { render :json => @djs.map(&:name) }
       end
     end    
   end
 end

html.erbファイル

  <script type="text/javascript">

$(function() {  
    $('#select_origin').autocomplete({
        source: '<%= djs_path(:json) %>'
      })

    $('.submit-comment').click(function(){
      var dj_name = $('#select_origin').val();
      $('#link_origin_id').val(dj_name);
    })

})

</script>

これは大きな助けです。

ユーザーの画像のURLを取得する必要がある場合に加えて、それは不可能かもしれません to_json. 。そのために、モデルに次のコードを追加します。

def avatar_url
    avatar.url(:thumb)
end

そして、その代わりにコントローラーで to_json 使用する as_json

respond_to do |format|
    format.json {render :json => @users.as_json(:only => [:id,:name,:username], :methods => [:avatar_url]) }
end 

「ソース」が比較的小さい場合、たとえば50の要素など、実装は異なる(そしてはるかに簡単な)ものでなければならないことに注意することが重要です。公式文書の4番目の段落で言及されています。

https://api.jqueryui.com/autocomplete/

ローカルデータを使用する場合、必要なのはデータを取得してオートコンプリートメソッドに渡すだけで、フィルタリングが行われます。用語が入力されるたびにサーバーに行き来する必要はありません。

function filterByTags(tags) {
  $("#stories-filter").autocomplete({
     source: tags,
     autoFocus: true
  });
}

$("#stories-filter").click(function() {
  $.ajax({
    dataType: 'json',
    method: 'GET',
    url: 'tags/index',
    data: $(this).data('project-id'),
    success: function (response) {
      if(response.success) {
        var tags = response.data.tags;
        filterByTags(tags);
      }
    },
    error: function (response) {
      if(response.status === 422) {
        var $errors = 'There are no tags in this project',
            $errorsContainer = $('.error-container');
        $errorsContainer.append($errors);
        $errorsContainer.show();
      }
    }
  });
});
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top