Rajko Marković Rajko Marković - 2 months ago 6
CSS Question

How to use JavaScript search on the same page while the user is still typing?

I'm trying to make a JavaScript search for a

div
within the same page. I'm currently using this code to display my search query:

$('.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();
});
});


Here's a demo of an example with HTML and CSS:

DEMO

So I want to display the
div
, while the user is still typing. I know there is a refresh function, but I just cannot understand JavaScript. I'm a newbie student.

Answer

With a bit of refactoring you can both handle the click on the Search button and updating the search results as you type on the text input. This should work:

function updateResults() {
    var query = $.trim($('.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();
    });
}

$('.form-search').on('submit',function(){return false;});
$('.form-search .btn').on('click', updateResults);
$('.search-query').on('input', updateResults);

Updated Jsfiddle: http://jsfiddle.net/1w8L0oeq/