Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery hide all divs except for the divs I search for [closed]

I want to create a search input for users to quickly find teachers for my school.

Teachers

The above is a horizontal scrollbar containing a lot of teachers. Every teacher in the scrollbar is wrapped in a seperate div called staff-container.

<div class="staff-container">
    <div class="staff">
        <div class="staff-picture">
            <img src="img/people/teachers/aiello.png" alt="" />
        </div>
        <p><span class="bold">Mrs. Aiello</span><br />
        Ext. 13328<br />
        Room 328/323<br />
        <a href="mailto:[email protected]">[email protected]</a></p>
    </div>
</div>

The above is the staff-container for Mr. Ahmed. Every teacher has the same exact structure in HTML.

When I type a teacher's name in the search and click the search button, I want the following to happen.

Search

I want all the staff-container's that don't match the search term to be hidden with display:none; by using JQuery.

I want the search to only look for the teacher name. In other words, only the <span class="bold">teacher</span> in each staff-container should be looked for by the search.

If no teacher matches the search term, I want all the teachers to be displayed. If nothing is searched, I want all the teachers to be displayed.

Search HTML:

<div class="search-container">
    <form class="form-search form-inline">
        <input type="text" class="input-medium search-query" placeholder="Search">
        <button type="submit" class="btn">Search</button>
    </form>
</div>

Here is a VERY simple fiddle

Check out the webpage I am adding the search to. It does not have the search on it yet.

I'm sorry if I'm asking too big of a question sad face, I just need help because I have never made a search in jquery.

edited to remove downvote

like image 388
Brett Merrifield Avatar asked Jun 07 '13 14:06

Brett Merrifield


2 Answers

Check jsfiddle:

http://jsfiddle.net/XjgR2/

$('.form-search').on('submit',function(){return false;});
$('.form-search .btn').on('click', function(e){
    var query = $.trim($(this).prevAll('.search-query').val()).toLowerCase();
    $('div.staff-container .bold').each(function(){
         var $this = $(this);
         if($this.text().toLowerCase().indexOf(query) === -1)
             $this.closest('div.staff-container').fadeOut();
        else $this.closest('div.staff-container').fadeIn();
    });
});
like image 91
A. Wolff Avatar answered Nov 12 '22 14:11

A. Wolff


Here is something you can do with css3 selectors. In your div staff-container create an attibute called teacher. For example

<div class='staff-container' teacher='John Dow'>.....</div>

Then in your jquery use the following css3 selector

var searchval = $('.search-query').val()
$("div[teacher*=" + searchval + "]").show();
like image 35
DevZer0 Avatar answered Nov 12 '22 13:11

DevZer0