Adam Tal
Adam Tal

Reputation: 921

Search within Bootstrap Tabs

I'm using Bootstrap 3 pill tabs and would like to offer a functionality similar to filtering a table with live.

In other words, as the user types - make irrelevant tabs disappear, so the user can tell that they do not contain the typed string.

I'm not sure how to go about this, any general ideas would be appreciated. Code snippets as well, obviously.

Upvotes: 0

Views: 2931

Answers (2)

max
max

Reputation: 8667

A little bit different approach (checks content of tabs, not the titles).

var tabLinks = $('.nav > li'),
  tabsContent = $('.tab-content > div'),
  tabContent = [],
  string,
  i,
  j;

for (i = 0; i < tabsContent.length; i++) {
  tabContent[i] = tabsContent.eq(i).text().toLowerCase();
}
$('input').on('input', function() {
  string = $(this).val().toLowerCase();
  for (j = 0; j < tabsContent.length; j++) {
    if (tabContent[j].indexOf(string) > -1) {
      tabLinks.eq(j).show();
      tabLinks.eq(j).find('a').tab('show');
    } else {
      tabLinks.eq(j).hide();
    }
  }
});

CODEPEN

Upvotes: 2

Sean Wessell
Sean Wessell

Reputation: 3510

$('#search').on('input', function() {
  var search = this.value;
  $('.nav.nav-pills li').hide().filter(function() {
    //get target from tabs anchor and create jQuery Object
    var $target = $($(this).find('a').attr('href'));
    //Return true if the text contains the search word
    return ($target.text().indexOf(search) != -1);
  }).show().eq(0).find('a').click();
  //get 1st item (index of 0) and click the anchor to set it to active and activate
  //the associated tab-pane
})

You could try something like this. https://jsfiddle.net/SeanWessell/dsnwkw66/

Upvotes: 2

Related Questions