Question

I understand this is a frequently discussed question. But none of the answers are satisfactory.

I am unable to reset / reinitialize a bootstrap modal, after it is hidden.

As suggested in one of the other threads, I have the following code:

$('#myModal').on('hidden', function() {
    $(this).data('modal', null);
});

After this, if the modal is shown again, the content added in the previous show still remains.

Here is the jsfiddle link that demonstrates the problem:

  1. After the modal is shown first time, if "save changes" clicked, it will add some dynamic elements to the modal.
  2. Then if close button clicked, modal gets hidden.
  3. if modal is invoked again, it shows the elements dynamically added during its previous invocation.

What is the best way to reset this modal.

As indicated earlier, the below code doesn't seem to work:

$(this).data('modal', null);

Other alternative would be to manually reset the fields to original state.

However, in my practical application, I am creating many dynamic and complex elements to the modal, so the option of resetting is tedious.

Was it helpful?

Solution

The modal is not aware of your input fields. You need to manually clear those within the hidden event:

$('#myModal').on('hidden', function() {
    $('inputEmail').val(null);
});

You could create a custom wrapper for the bootstrap modal where you give it an array of jQuery objects to clear:

var myModal = function (id, inputs) {
    $(id).on('hidden', function () {
        $.each(inputs, function(i, input) {
            input.val(null);
        });
    });
    return $(id).modal();
};

This is just a rough idea....

The best method is to use a JavaScript framework, like Knockout.js, Angular.js, Backbone.js, or others. They can really help you out with similar event issues.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top