3

I'm trying to build a "search in the shown elements" function with jquery and css. Here's what I got so far:

http://jsfiddle.net/jonigiuro/wTjzc/

Now I need to add a little feature and I don't know where to start. Basically, when you write something in the search field, the corresponding letters should be highlighted in the list (see screenshot, the blue highlighted part)

enter image description here

Here's the script so far:

var FilterParticipants = function(options) {
    this.options = options;
    this.participantList = [];

    this.init = function() {

        var self = this;
        //GENERATE PARTICIPANTS OPBJECT
        for(var i = 0; i < this.options.participantBox.length ; i++) {
            this.participantList.push({
                element: this.options.participantBox.eq(i),
                name: this.options.participantBox.eq(i).find('.name').text().toLowerCase()
            })
        }
        //ADD EVENT LISTENER
        this.options.searchField.on('keyup', function() {
            self.filter($(this).val());

        })
    }

    this.filter = function( string ) {
        var list = this.participantList;
        for(var i = 0 ; i < this.participantList.length; i++) {
            var currentItem = list[i];
            //COMPARE THE INPUT WITH THE PARTICIPANTS OBJECT (NAME)
            if( currentItem.name.indexOf(string.toLowerCase()) == -1) {
                 currentItem.element.addClass('hidden');
             } else {
                 currentItem.element.removeClass('hidden');
             }
         }
    }

    this.init();
}

var filterParticipants = new FilterParticipants({
    searchField: $('#participants-field'),
    participantBox: $('.single_participant'),
    nameClass: 'name'
});
Jonas Grumann
  • 10,438
  • 2
  • 22
  • 40

2 Answers2

3

I think you're just complicating things too much... You can do this easily in a few lines. Hope this helps:

var $search = $('#participants-field');
var $names = $('.single_participant p');

$search.keyup(function(){
  var match = RegExp(this.value, 'gi'); // case-insensitive
  $names
    .hide()
    .filter(function(){ return match.test($(this).text()) })
    .show()
    .html(function(){
      if (!$search.val()) return $(this).text();
      return $(this).text().replace(match, '<span class="highlight">$&</span>');
    });
});

I used hide and show because it feels snappier but you can use CSS3 animations and classes like you were doing.

Demo: http://jsfiddle.net/elclanrs/wTjzc/8/

elclanrs
  • 92,861
  • 21
  • 134
  • 171
0

Here`s the way to do it with jQuery autocomplete so question
If you want to build it on your own you can do the following:
1. Get the data of every item.
2. Make render function in which you will substitute say "Fir" in Fire word to Fire
3. Every time you change the text in the input you can go through the items and perform substitution.

Community
  • 1
  • 1
Yaroslav Yakovlev
  • 6,303
  • 6
  • 39
  • 59