filter.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. /**
  2. * create a simple search filter thing for a list
  3. */
  4. (function ($) {
  5. Drupal.Filter = function (list, title, type, parent){
  6. this.list = list;
  7. this.title = title;
  8. //provide defaults for type and parent so bad things don't happen
  9. if (!type) { var type = '*'; }
  10. this.type = type;
  11. if (!parent) { var parent = list; }
  12. this.parent = parent;
  13. this.init();
  14. }
  15. Drupal.Filter.prototype = {
  16. init : function(){
  17. this.wrapper = $('<div class="filter-wrapper"></div>');
  18. if(this.title){
  19. this.title = '<h3>' + this.title + '</h3>';
  20. this.wrapper.append(this.title);
  21. }
  22. this.input = $('<input type="text" class="filter" />');
  23. this.wrapper.append(this.input);
  24. $(this.parent).append(this.wrapper);
  25. this.createHandlers();
  26. },
  27. createHandlers : function(){
  28. var self = this;
  29. $(this.input).keyup(function(e){
  30. self.filter();
  31. });
  32. },
  33. filter : function(){
  34. //show all first off
  35. $('*', this.list).show();
  36. //hide ignored items
  37. if(this.input.val()) {
  38. $('*', this.list).not(this.type).hide();
  39. }
  40. var regex = new RegExp(this.input.val(), 'i');
  41. var self = this;
  42. $(this.type, this.list).each(function(ind, el) {
  43. var string = self.strip(el.innerHTML);
  44. if(!regex.test(string)){
  45. $(el).hide();
  46. } else { //show the parent and any labels or whatever in the parent
  47. var parent = $(el).parent().show();
  48. $('*', parent).not(self.type).show();
  49. }
  50. });
  51. },
  52. strip : function(string){
  53. var strip = /<([^<|^>]*)>/i;
  54. while(strip.test(string)){
  55. var matches = string.match(strip);
  56. string = string.replace(strip, '');
  57. }
  58. return string;
  59. }
  60. };
  61. })(jQuery);