1

I have a set of divisions;

<div id="people">
  <div>
    <p>Joe Blogs</p>
    <img src=".." />
  </div>
  <div>
    <p>Jane Doe</p>
    <img src=".." />
  </div>
</div>

I want to be able to have an input text box, which when typed in, it will search through the divisions (in the p tag) and if the string matches in part or whole it will show the division, otherwise hide all the non matching divisions.

How would I best go about this using jQuery?

Many thanks?

Simon R
  • 3,732
  • 4
  • 31
  • 39

3 Answers3

2

Depending on the size of the list, the :contains selector does a good job.

DEMO

$(function() {
  $("#filter").on("keyup",function() {
    var val = $(this).val();
    var people = $("#people > div");
    if (val=="") people.show();
    else {
      people.hide()
      $("#people > div:contains('"+val+"')").show();
    }
  });
});

This is case sensitive by the way For a clever case in sensitive method, look here https://stackoverflow.com/a/4936066/295783

Community
  • 1
  • 1
mplungjan
  • 169,008
  • 28
  • 173
  • 236
1

DEMO

REFERENCE

var results = [];
$("#people p").each(function(){
   results.push($(this).text());
});

jQuery('#filter').on('keyup', function(event){
    var term = jQuery(this).val();
    var htm = '';
    jQuery('#result').empty().hide();

    //Keys with codes 40 and below are special (enter, arrow keys, escape, etc.), Key code 8 is backspace.
    if(event.keyCode > 40 || event.keyCode <91  || event.keyCode == 8 ||
      event.keyCode == 20 || event.keyCode == 16 || event.keyCode == 9 ||
      event.keyCode == 37 || event.keyCode == 38 || event.keyCode == 39 ||
      event.keyCode == 40) {
        for(x in results){
            var match = results[x];
            if(match.toLowerCase().indexOf(term.toLowerCase()) != -1){
                var o = '<b><u>'+term+'</u></b>';
                var a = match.replace(term, o);
                htm += '<li>'+a+'</li>';
            }
        }
        var output = '<ol>' + htm + '</ol>';
        if (htm.length > 0) {
            jQuery('#result').show().append(output);
        }
    }
    if(term.length == 0){
        jQuery('#result').empty().hide();
    }
});
halilb
  • 4,055
  • 1
  • 23
  • 31
Arvind Bhardwaj
  • 5,231
  • 5
  • 35
  • 49
1

It is better to filter data using javascript objects (you get data from server, filter them and display with templating engine (jsrender or anything else)).

For your example it could look like:

var timer,
    items = $('#people > div');

var refreshFilter = function(txt) {
    clearTimeout(timer);
    timer = setTimeout(function() {
        var showItems = items.find("p:contains('" + txt + "')").closest('div').show();
        items.not(showItems).hide();
    }, 200);
};

$('#search').keyup(function () {
    refreshFilter(this.value);
});

Demo: http://jsfiddle.net/rptgf/

webdeveloper
  • 17,174
  • 3
  • 48
  • 47