Bootstrap toggle buttons inside popover content not working

Nayana_Das picture Nayana_Das · Jul 18, 2014 · Viewed 10.3k times · Source

I have made a jsFiddle where i use twitter bootstrap toggle buttons & popover.

HTML:

<div class="btn-group btn-toggle">
  <button class="btn btn-sm btn-info">On</button>
  <button class="btn btn-sm btn-primary active">Off</button>
</div>

<button id="popbutton" class="btn btn-lg btn-warn">pop up</button>

JS:

var popupElement = '<div class="btn-group btn-toggle"><button class="btn btn-sm btn-  info">On</button><button class="btn btn-sm btn-primary active">Off</button></div>';

$('#popbutton').popover({
  animation: true,
  content: popupElement,
  html: true
});


$('.btn-toggle').click(function () {
   $(this).find('.btn').toggleClass('active');

   if ($(this).find('.btn-primary').size() > 0) {
      $(this).find('.btn').toggleClass('btn-primary');
   }
   if ($(this).find('.btn-danger').size() > 0) {
      $(this).find('.btn').toggleClass('btn-danger');
   }
   if ($(this).find('.btn-success').size() > 0) {
      $(this).find('.btn').toggleClass('btn-success');
   }
   if ($(this).find('.btn-info').size() > 0) {
      $(this).find('.btn').toggleClass('btn-info');
   }

  $(this).find('.btn').toggleClass('btn-default');

});

The toggle button works, but when i use the same buttons inside a popover, it won't work.

Please suggest a method.

Answer

koala_dev picture koala_dev · Jul 18, 2014

Since your popover buttons do not exist at load time you need to use event delegation. Also instead of size() (which is deprecated as of jQuery 1.8) you should use the length property:

$('body').on('click','.btn-toggle',function () {
    $(this).find('.btn').toggleClass('active');

    if ($(this).find('.btn-primary').length > 0) {
        $(this).find('.btn').toggleClass('btn-primary');
    }
    if ($(this).find('.btn-danger').length > 0) {
        $(this).find('.btn').toggleClass('btn-danger');
    }
    if ($(this).find('.btn-success').length > 0) {
        $(this).find('.btn').toggleClass('btn-success');
    }
    if ($(this).find('.btn-info').length > 0) {
        $(this).find('.btn').toggleClass('btn-info');
    }

    $(this).find('.btn').toggleClass('btn-default');
});

Updated fiddle