jqueryjquery-mobilejquery-mobile-collapsible

How to remove dynamically added collapsible in JQM


I am building a UI with the reference of Jquery Mobile but stuck in a idea how to remove a dynamically added collapsible in the example given in Jquery Mobile Demos.

http://demos.jquerymobile.com/1.4.5/collapsible-dynamic/

I have generated an example for the same. JSBIN

JS Used:

console.log("DOM Load");
$( document ).on( "pagecreate", function() {
    var nextId = 1;
    $("#add").click(function() {
    nextId++;
      var content = "";
    content += "<div data-role='collapsible' id='set" + nextId + "'>";
    content += "<h3>Section " + nextId + "</h3>";
    content += "<p>I am the collapsible content in a set so this feels like an accordion. I am hidden by default because I have the 'collapsed' state; you need to expand the header to see me.</p>";
    content += "<button id='removeStyle" + nextId + "' class='removeStyleBtn ui-btn ui-btn-b ui-shadow ui-corner-all ui-mini'>Remove</button></div>";

    $( "#set" ).append( content ).collapsibleset( "refresh" );
    //$("#set" + nextId+ " :button").button().button('refresh');
    $("#set" + nextId).collapsible( "expand" );
    console.log("collapsible set " + nextId + " added !!!");
  });
  console.log("pagecreate triggered !!!");

  $(".removeStyleBtn").click(function() {
    console.log("Removed Element !!!!!");
  });

});

Thanks


Solution

  • id need to be unique per element so remove button id(not needed in your case)

    And then do:-

    $(document).on("click",".removeStyleBtn",function() {
        $(this).closest('div[data-role="collapsible"]').remove();
    });
    

    Put this code outside of $(document).ready(){..});

    Output:- https://jsbin.com/vuyehocate/edit?html,js