Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

            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. 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.

So I added in :

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

... Enter their 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 retrieves the data for the textbox and doesn't delimit the returned checkboxes at all. Is there a way I can do this ?

like image 775
Simon Kiely Avatar asked Jan 17 '23 05:01

Simon Kiely


1 Answers

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/

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/

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.

like image 82
nnnnnn Avatar answered Jan 20 '23 16:01

nnnnnn