Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamical search-function to show/hide divs

this is my first post on StackOverflow. I hope it doesn't go horribly wrong.

<input type="Text" id="filterTextBox" placeholder="Filter by name"/>
<script type="text/javascript" src="/resources/events.js"></script>
<script>
$("#filterTextBox").on("keyup", function () {
    var search = this.value;
    $(".kurssikurssi").show().filter(function () {
        return $(".course", this).text().indexOf(search) < 0;
    }).hide();        
});

</script>

I have a javascript snippet like this on my school project, which can be found here: http://www.cc.puv.fi/~e1301192/projekti/tulos.html

So the search bar at the bottom is supposed to filter divs and display only those, that contain certain keyword. (t.ex, if you type Digital Electronics, it will display only Divs that contain text "Digital Electronics II" and "Digital Electronics". Right now, if I type random gibberish, it hides everything like it's supposed to, but when I type in the beginning of a course name, it will not hide the courses that dont contain the certain text-string.

Here is an example that I used (which works fine): http://jsfiddle.net/Da4mX/

Hard to explain, but I hope you realize if you try the search-function on my page. Also, I'm pretty new to javascript, and I get the part where you set the searchbox's string as var search, the rest I'm not so sure about.

Please help me break down the script, and possibly point where I'm going wrong, and how to overcome the problem.

like image 712
Hexal Avatar asked Oct 19 '22 19:10

Hexal


1 Answers

in your case I think you show and hide the parent of courses so you can try

$("#filterTextBox").on("keyup", function () {
    var search = $(this).val().trim().toLowerCase();
    $(".course").show().filter(function () {
        return $(this).text().toLowerCase().indexOf(search) < 0;
    }).hide();        
});
like image 116
Mohamed-Yousef Avatar answered Oct 30 '22 21:10

Mohamed-Yousef