[英]Dynamic search results on keystroke
I have a list of items stored in a database. 我有一个存储在数据库中的项目列表。
I am using a foreach to list the items returned with a checkbox next to each item like so: 我使用foreach列出返回的项目,每个项目旁边都有一个复选框,如下所示:
var db = Database.Open("database");
var sql = "SELECT * from table";
var result = db.Query(sql);
... ...
@{foreach (var user in result) {
<tr><td>@table.attribute</td> <td>@table.secondAttribute @table.thirdAttribute</td>
<td><input type="checkbox" name="attribute" value="attribute" /></td></tr>
The functionality I would like to have is a textbox which, upon the user typing a letter, would limit the number of items listed by my foreach based on what character the user enters. 我想要的功能是一个文本框,当用户键入一个字母时,将根据用户输入的字符限制我的foreach列出的项目数。 So I've tried to use the JQuery autoComplete module, but I'm not entirely sure how to use it in this case, or even if it is possible.
所以我试图使用JQuery autoComplete模块,但我不完全确定如何在这种情况下使用它,或者即使它是可能的。
So I added in : 所以我补充说:
$(function(){
$('#name').autocomplete({source:'getUsers'});
});
... Enter their name: ...输入他们的名字:
And then in getUsers : 然后在getUsers中:
@{
var db = Database.Open("database");
var term = Request.QueryString["term"] + "%";
var sql = "SELECT * from table where attribute LIKE @0 OR secondAttribute LIKE @0 OR thirdAttribute LIKE @0";
var result = db.Query(sql, term);
var data = result.Select(p => new{label = p.attribute + " " + p.secondAttribute});
Json.Write(data, Response.Output);
}
This, of course, just retrieves the data for the textbox and doesn't delimit the returned checkboxes at all. 当然,这只是检索文本框的数据,并且根本不会分隔返回的复选框。 Is there a way I can do this ?
有没有办法可以做到这一点?
If client-side only search is acceptable as per your comment, here's a really simple way to do it: 如果根据您的评论,只接受客户端搜索,这是一个非常简单的方法:
$(document).ready(function() {
var $rows = $("tr");
$("#yoursearchinput").keyup(function() {
var val = $.trim(this.value);
if (val === "")
$rows.show();
else {
$rows.hide();
$rows.has("td:contains(" + val + ")").show();
}
});
});
Demo: http://jsfiddle.net/k5hkR/ 演示: http : //jsfiddle.net/k5hkR/
Note that the above will do a case sensitive search. 请注意,上面将进行区分大小写的搜索。 Here is a slightly more complicated version that does a case insensitive search:
这是一个稍微复杂的版本,它执行不区分大小写的搜索:
$(function() {
var $cells = $("td");
$("#search").keyup(function() {
var val = $.trim(this.value).toUpperCase();
if (val === "")
$cells.parent().show();
else {
$cells.parent().hide();
$cells.filter(function() {
return -1 != $(this).text().toUpperCase().indexOf(val);
}).parent().show();
}
});
});
Demo: http://jsfiddle.net/k5hkR/1/ 演示: http : //jsfiddle.net/k5hkR/1/
The second solution is just something I whipped up to give you the general idea - obviously it can be tidied up and made more efficient. 第二种解决方案只是我掀起的一些东西,为您提供了一般性的想法 - 显然它可以整理并提高效率。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.