开发者

jQuery UI Autocomplete in Rails, updating hidden field with ID attribute

I have this in my form, it's really simple:

<script>
    $(function() {
        var availableProducts = [
             <% @products.each do |p| %>"<%= p.id %> <%= p.title %> (<%= p.product_type.name %>)",<% end %>
             ""
        ];
        $( "#tags" ).autocomplete({
            source: availableProducts
        });
    });
</script>

That gives me lists of things like 1 Title (Trade Paperback). All rails needs of course, is the id attribute. I'd planned on updating a hidden field with the attribute, using the select: event, but I'm not quite sure how to extract just the id from the data source to update the hidden field with. Should I change the data source to something that can have keys? Like JSON? I still wouldn't know how to extract from that.

Here's what the above code looks like in straight html:

<script>
    $(function() {
        var availableProducts = [
              "1 Test Title (eBook)",
              "2 Another Test Title (eBook)",
              ""
        ];
        $( "#products" ).autocomplete({
            source: availableProducts
        });
    });
</scr开发者_JAVA百科ipt>


Your source should be an array of {value: , label: } pairs. The labels are what will be displayed and autocompleted on, but then you can store the value in a hidden input.

Here's an example:

http://jsfiddle.net/vZeHr/4/

and check out this sample on the jquery-ui docs page

http://jqueryui.com/demos/autocomplete/#custom-data

To generate the array from rails, you can do something like

var availableProducts = <%= @products.collect { :label => p.title, :value => p.id }.to_json ->;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜