jquery 插件实现百度式的autocomplete

百度输入so就能提示sogou等等,一点击就把该值上屏。这个功能用jquery.plugin可以实现。
在github上面jquery 插件有两种方式:jquery-tokeninput和jqueryui的autocomplete。前者我用了下,对于jquery-tokeninput提供的样式和样式的自定义不够满意。样式太死,太少了。因为它把原来的<input type='text'>隐藏了用div ul li等模拟了,因此导致样式效果不够好。
因此我看到了https://github.com/crowdint/rails3-jquery-autocomplete。这个和rails集成了。但是可惜,这个程序员集成的很烂。很不灵活。连关联查询显示relation Model数据并显示目前都不支持。所以我自己直接用jquery-tokeninput实现了。真的没有必要用rails3-jquery-autocomplete这玩意。
下载jqueryui后看它的demo中的源代码,很容易实现。

javascript:
$(function() {
function log( message ) {
$( "<div/>" ).text( message ).prependTo( "#log" );
$( "#log" ).scrollTop( 0 );
}

$( "#city" ).autocomplete({
source: function( request, response ) {
$.ajax({
url: "/orders/search_dishes?store_id=#{params[:store_id]}&q=" + $("#city").val(),
dataType: "json",
data: {
featureClass: "P",
style: "full",
maxRows: 12,
name_startsWith: request.term
},
success: function(d) {
response($.map(d,function(item){
return {
label: item.name,
value: item.name
}
}));
}
});
},
minLength: 2,
select: function( event, ui ) {
log( ui.item ?
"Selected: " + ui.item.label :
"Nothing selected, input was " + this.value);
},
open: function() {
$( this ).removeClass( "ui-corner-all" ).addClass( "ui-corner-top" );
},
close: function() {
$( this ).removeClass( "ui-corner-top" ).addClass( "ui-corner-all" );
}
});
});
.demo
.ui-widget
label for="city"
| Your city:
input id="city"
.ui-widget style="margin-top:2em; font-family:Arial"
| Result:
#log style="height: 200px; width: 300px; overflow: auto;" class="ui-widget-content"


controller.rb:
def search_dishes
store = Store.find(params[:store_id])
dishcates_ids = store.dishcates.collect{|f| f.id}
respond_to do |format|
format.json {
render json: dishes.as_json(
:include => { :dishcate => {
:only => [:name] } },
:only => [:name, :price]
)
}
end
end


routes.rb:加上
get 'orders/search_dishes' => 'orders#search_dishes'
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值