-1

I have a checkbox containing a class name "checkbox-button".when the page load then below function is execute perfectly.But when a newly created checkbox appended on jquery success then the below function doesn't execute.

$(function() {
  $('.button-checkbox').each(function() {
    var $widget = $(this),
      $button = $widget.find('button'),
      $checkbox = $widget.find('input:checkbox'),
      color = $button.data('color'),
      settings = {
        on: {
          icon: 'glyphicon glyphicon-check'
        },
        off: {
          icon: 'glyphicon glyphicon-unchecked'
        }
      };

    // Event Handlers
    $button.on('click', function() {
      $checkbox.prop('checked', !$checkbox.is(':checked'));
      $checkbox.triggerHandler('change');
      updateDisplay();
    });

    $checkbox.on('change', function() {
      updateDisplay();
    });

    function updateDisplay() {
      var isChecked = $checkbox.is(':checked');
      $button.data('state', (isChecked) ? "on" : "off");

      // Set the button's icon
      $button.find('.state-icon').removeClass().addClass('state-icon ' + settings[$button.data('state')].icon);
    }

    function init() {
      updateDisplay();

      // Inject the icon if applicable
      if ($button.find('.state-icon').length == 0) {
        $button.prepend('<i class="state-icon ' + settings[$button.data('state')].icon + '"></i> ');
      }
    }
    init();
  });
});
Rory McCrossan
  • 306,214
  • 37
  • 269
  • 303
Andy
  • 23
  • 4

1 Answers1

0

I might be wrong but it looks like a problem with event delegation https://learn.jquery.com/events/event-delegation/

This is what you need for that to work:

// Attach a delegated event handler
$( "#list" ).on( "click", "a", function( event ) {
    event.preventDefault();
    console.log( $( this ).text() );
});

If your HTML is something like:

<div class="list-checkboxes">
    <div class="list__item">
      <input type="checkbox" name="checkbox-1" id="checkbox-1">
    </div><!-- /.list__item -->

    <div class="list__item">
      <input type="checkbox" name="checkbox-2" id="checkbox-2">
    </div><!-- /.list__item -->

    <div class="list__item">
      <input type="checkbox" name="checkbox-3" id="checkbox-3">
    </div><!-- /.list__item -->
  </div><!-- /.list-checkboxes -->

You can do the following to make sure your function is triggered on appended checkboxes:

$( ".list-checkboxes" ).on( "change", "input[type='checkbox']", function( event ) {
    event.preventDefault();
    console.log( 'this should trigger on the appended checkboxes as well' );
});