Rails 文本框输入自动查询(无刷新)..
哎,太难了,本来可以直接用 select2 来做的,有些问题导致得自己来写一个,这里就记录一下。
首先,写一个 input 输入框以及显示查询结果的 div:
= f.text_field :company, hide_label: true, required: true, class: 'form-control', id: "company-field", placeholder: "所属公司"
.searchresult#searchresult data-url=query_company_users_path
然后是... Css 样式,
.company-div {
padding: 6px 12px;
cursor: pointer;
&:hover {
background-color: #e0e0ee;
}
}
.searchresult {
max-height: 100px;
overflow-x:auto;
overflow-y:auto;
background: #FFFFFF;
border-bottom-left-radius: 4px;
border-bottom-right-radius: 4px;
border: 1px solid #ccc;
position: absolute;
width: 95%;
display: none;
}
@media screen and (max-width: 767px) {
.searchresult {
width: 92%;
}
}
最后就是激动人心的 JQ 代码了。
$('#company-field').on('keyup click', function (evt) {
let k = window.event ? evt.keyCode : evt.which;
if ($(this).val().trim().replace(/\s/g,"") == ""){
$('.error').show().text('不能为空')
$(this).addClass('is-invalid')
$('#searchresult').hide().empty()
return
}else{
$('.error').hide()
$(this).removeClass('is-invalid')
}
if ($(this).val() != "" && k != 38 && k != 40 && k != 13) {
$('#searchresult').show().empty()
$('<div class="company-div">加载中...</div>').appendTo('#searchresult')
$.ajax({
type: 'POST',
url: $('.searchresult').data('url'),
async: true,
dataType: 'JSON',
data: {company: $(this).val().trim().replace(/\s/g,"")},
success: function(data){
if (data.msg.length > 0){
$('#searchresult').empty()
for(let i = 0; i < data.msg.length; i++){
$('<div class="company-div">'+ data.msg[i].company +'</div>').appendTo('#searchresult')
}
$('.company-div').on('click', function(){
$('#company-field').val($(this).text())
$('#searchresult').hide().empty()
})
}else{
$('#searchresult').hide().empty()
}
}
})
}
})
$('.verification-codes-new-page').click(function(e){
var e = e || window.event;
var elem = e.target;
if(!$(elem).is('.searchresult')){
$('#searchresult').hide().empty()
}
})
Controller 里面只需要:
@companys = Profile.where("company like ?","%#{params[:company]}%").select("distinct company ")
render json: { msg: @companys }
ok,解决。