我正在尝试设置一个简单的搜索栏来显示/隐藏我的rails应用中的内容。具体来说,尝试允许某人通过我的聊天室中的用户名搜索特定用户,这些用户正在使用每个阵列的Rails显示。我查看了这两个问题以获取指导,但仍然没有将其付诸实施 - In-page search using contains() to show/hide div content和Dynamical search-function to show/hide divs。每当我输入用户名时,虽然在搜索框中没有显示任何内容。我在下面列出了我的代码,对此事的任何帮助都会很棒。非常感谢你!
Index.html.erb
<div class="col-md-4">
<form name="searchBox">
Search for a User: <input type="text" name="keyword" />
<input type="button" value="Search" onClick="searchFunction()" />
</form>
<% (User.all - [current_user]).each do |user| %>
<div class="box2" style="display:none" id="searchable">
<%= image_tag user.background, height: 95, width: 165, class: "css-style4" %>
<strong><%= link_to user.username, direct_message_path(user.id), data: {behavior: "chatroom-link", chatroom_id: Chatroom.direct_message_for_users([current_user, user]).id} %></strong>
</div>
<% end %>
</div>
chatroomsearch.js
$(document).on('turbolinks:load',function(){
function searchFunction() {
$("#searchable")
.hide()
.filter(":contains('" + $("input[name='keyword']").val() + "')")
.show();
}
}
答案 0 :(得分:1)
您的问题在这一行:
<div class="box2" style="display:none" id="searchable">
ID必须是唯一的。因此,删除它们并将它们用作类中的类:
<div class="box2 searchable" style="display:none">
这样你就需要改变选择器:
$("#searchable")
为:
$(".searchable")
摘录:
function searchFunction() {
$(".searchable")
.hide()
.filter(":contains('" + $("input[name='keyword']").val() + "')")
.show();
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<div class="col-md-4">
<form name="searchBox">
Search for a User: <input type="text" name="keyword"/>
<input type="button" value="Search" onClick="searchFunction()"/>
</form>
<div class="box2 searchable" style="display:none">
<strong><a href='/direct_messages/1' data-behavior="chatroom-link"
data-chatroom_id="Chatroom.direct_message_for_users([current_user, user]).id">Rodrigo1 Williams</a></strong>
</div>
<div class="box2 searchable" style="display:none">
<strong><a href='/direct_messages/1' data-behavior="chatroom-link"
data-chatroom_id="Chatroom.direct_message_for_users([current_user, user]).id">Rodrigo2 Williams</a></strong>
</div>
</div>