[javascript] How to reset the bootstrap modal when it gets closed and open it fresh again?

I have a list box in the bootstrap modal and a button. When the button is clicked a new button gets rendered inside a div in the modal. When I close the modal and reopen it, the last operation performed on the modal like the button rendered earlier is still present in the modal.

How do reset the modal so that when the modal is opened again, the button is not present and user can again select the option from the list box and click on the button to render a new button and so on.

<!-- Modal -->
<div
  class="modal fade"
  id="myModal"
  tabindex="-1"
  role="dialog"
  aria-labelledby="myModalLabel"
  aria-hidden="true"
>
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal">
          <span aria-hidden="true">&times;</span
          ><span class="sr-only">Close</span>
        </button>
        <h4 class="modal-title" id="myModalLabel">Select Language</h4>
      </div>
      <div class="modal-body">
        <button type="button" class="btn" data-dismiss="modal">Close</button>
        <button type="button" class="btn" id="submit_form">Submit</button>

        <div class="modal-body1">
          <div id="placeholder-div1"></div>
        </div>
      </div>

      <div class="modal-footer">
        <script>
          $("#submit_form").on("click", function () {
            $(".modal-body1").html("<h3>test</h3>");
          });
        </script>

        <script>
          $(function () {
            $(".modal-footer").click(function () {
              $(".modal").modal("hide");
            });
          });
        </script>
      </div>
    </div>
  </div>
</div>

-- Update ---

Why doesn't this work?

<script type="text/javascript">
  $(function () {
    $("#myModal").on("hidden.bs.modal", function (e) {
      console.log("Modal hidden");
      $("#placeholder-div1").html("");
    });
  });
</script>

This question is related to javascript jquery html twitter-bootstrap

The answer is


/* this will change the HTML content with the new HTML that you want to update in your modal without too many resets... */

var = ""; //HTML to be changed 

$(".classbuttonClicked").click(function() {
    $('#ModalDivToChange').html(var);
    $('#myModal').modal('show');
});

(function(){
        $(".modal").on("hidden.bs.modal", function(){
            $(this).removeData();
        });
});

This is perfect solution to remove contact while hide/close bootstrap modal.


Reset form inside the modal. Sample Code:

$('#myModal').on('hide.bs.modal', '#myModal', function (e) {
    $('#myModal form')[0].reset();
});

The below statements show how to open/reopen Modal without using bootstrap.

Add two classes in css

And then use the below jQuery to reopen the modal if it is closed.

.hide_block
 {
   display:none  !important;
 }

 .display_block
 {
    display:block !important;
 } 

 $("#Modal").removeClass('hide_block');
 $("#Modal").addClass('display_block');
 $("Modal").show("slow");

It worked fine for me :)


also, you can clone your modal before open ;)

$('#myModal')
    .clone()
    .modal()
    .on('hidden.bs.modal', function(e) {
        $(this).remove();
    });

That's works for me accurately

let template = null;
    $('.modal').on('show.bs.modal', function(event) {
      template = $(this).html();
    });

    $('.modal').on('hidden.bs.modal', function(e) {
      $(this).html(template);
    });

Using BS 3.3.7

$("#yourModal").on('hidden.bs.modal', function () {
    $(this).data('bs.modal', null); // will clear all element inside modal
});

Tried it and working well

$('#MyModal').on('hidden.bs.modal', function () {
    $(this).find('form').trigger('reset');
})

reset is dom build-in funtion, you can also use $(this).find('form')[0].reset();

And Bootstrap's modal class exposes a few events for hooking into modal functionality, detail at here.

hide.bs.modal This event is fired immediately when the hide instance method has been called.

hidden.bs.modal This event is fired when the modal has finished being hidden from the user (will wait for CSS transitions to complete).


I am using BS 3.3.7 and i have a problem when i open a modal then close it, the modal contents keep on the client side no html("") no clear at all. So i used this to remove completely the code inside the modal div. Well, you may ask why the padding-right code, in chrome for windows when open a modal from another modal and close this second modal the stays with a 17px padding right. Hope it helps...

$(document)
.on('shown.bs.modal', '.modal', function () { 
    $(document.body).addClass('modal-open') 
})
.on('hidden.bs.modal', '.modal', function () { 
    $(document.body).removeClass('modal-open') 
    $(document.body).css("padding-right", "0px");
 $(this).removeData('bs.modal').find(".modal-dialog").empty();
})

Here's an alternative solution.

If you're doing a lot of changes to the DOM (add/removing elements and classes), there could be several things that need to be "reset." Rather than clearing each element when the modal closes, you could reset the entire modal everytime it's reopened.

Sample code:

(function(){

    var template = null

    $('.modal').on('show.bs.modal', function (event) {
        if (template == null) {
            template = $(this).html()
        } else {
            $(this).html(template)
        }
        // other initialization here, if you want to
    })

})()

You can still write your initial state in HTML without worrying too much about what will happen to it later. You can write your UI JS code without worrying about having to clean up later. Each time the modal is relaunched it will be reset to the exact same state it was in the first time.


Edit: Here's a version that should handle multiple modals (I haven't tested it)...

(function(){

    $('.modal').on('show.bs.modal', function (event) {
        if (!$(this).data('template')) {
            $(this).data('template', $(this).html())
        } else {
            $(this).html($this.data('template'))
        }
        // other initialization here, if you want to
    })

})()

Sample code:

 $(document).on('hide.bs.modal', '#basicModal', function (e) {
        $('#basicModal').empty();
    });

you can try this

$('body').on('hidden.bs.modal', '.modal', function () {
     $(this).removeData('bs.modal');
});

It will remove all the data from the model and reset it.


Try cloning, then removing and re-adding the element when the modal is hidden. This should keep all events, though I haven't thoroughly tested this with all versions of everything.

var originalModal = $('#myModal').clone();
$(document).on('#myModal', 'hidden.bs.modal', function () {
    $('#myModal').remove();
    var myClone = originalModal.clone();
    $('body').append(myClone);
});

To reset all the input fields in a modal use the following.

$(".modal-body input").val("")

What helped for me, was to put the following line in the ready function:

$(document).ready(function()
{
    ..
    ...

    // codes works on all bootstrap modal windows in application
    $('.modal').on('hidden.bs.modal', function(e)
    { 
        $(this).removeData();
    }) ;

    ...
    ..
});

When a modal window is closed and opened again, the previous entered and selected values, will be reset to the initial values.

I hope this will help you as well!


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

Examples related to twitter-bootstrap

Bootstrap 4: responsive sidebar menu to top navbar CSS class for pointer cursor How to install popper.js with Bootstrap 4? Change arrow colors in Bootstraps carousel Search input with an icon Bootstrap 4 bootstrap 4 responsive utilities visible / hidden xs sm lg not working bootstrap.min.js:6 Uncaught Error: Bootstrap dropdown require Popper.js Bootstrap 4 - Inline List? Bootstrap 4, how to make a col have a height of 100%? Bootstrap 4: Multilevel Dropdown Inside Navigation