Dynamic search results on keystrokes

I have a list of items stored in a database.

I use foreach to list the returned items with a checkbox next to each item like this:

            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 that, when a letter is entered, limits the number of items listed by my foreach based on what the user is typing in. So I tried using the JQuery autocomplete module, but I'm not really sure how to use it in this case, or even if it's possible.

So I added:

 $(function(){
            $('#name').autocomplete({source:'getUsers'});
        });

      

... Enter your name:                 

And then in 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 fetches the data for the textbox and doesn't limit the returned checkboxes at all. Is there a way I can do this?

+3


source to share


1 answer


If client-side search is only possible as per your comment, here's a really easy 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/

Note that the above will perform a case sensitive search. Here's a slightly more complex version that makes case insensitive:



$(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/

The second solution is what I whipped up to give you a general idea - obviously it can be removed and made more efficient.

+6


source







All Articles