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

JavascriptJqueryHtmlTwitter Bootstrap

Javascript Problem Overview


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>

Javascript Solutions


Solution 1 - Javascript

Just reset any content manually when modal is hidden:

$(".modal").on("hidden.bs.modal", function(){
    $(".modal-body1").html("");
});

There is more events. More about them here

$(document).ready(function() {
  $(".modal").on("hidden.bs.modal", function() {
    $(".modal-body1").html("Where did he go?!?!?!");
  });
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/js/bootstrap.min.js"></script>

<button type="button" class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal">
  Launch modal
</button>

<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">Modal title</h4>
      </div>
      <div class="modal-body">
        <div class='modal-body1'>
          <h3>Close and open, I will be gone!</h3>
        </div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
      </div>
    </div>
  </div>
</div>

Solution 2 - Javascript

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).

Solution 3 - Javascript

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!

Solution 4 - Javascript

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);
});

Solution 5 - Javascript

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

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

Solution 6 - Javascript

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
	})
		
})()

Solution 7 - Javascript

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

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

Solution 8 - Javascript

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);
    });

Solution 9 - Javascript

also, you can clone your modal before open ;)

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

Solution 10 - Javascript

Reset form elements ( Works with bootstrap 5 as well). Sample code :

$(document).on("hidden.bs.modal", "#modalid", function () {
  $(this).find('#form')[0].reset();
});

Solution 11 - Javascript

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.

Solution 12 - Javascript

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();
})

Solution 13 - Javascript

Sample code:

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

Solution 14 - Javascript

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 :)

Solution 15 - Javascript

/* 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');
});

Solution 16 - Javascript

Using BS 3.3.7

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

Solution 17 - Javascript

Reset form inside the modal. Sample Code:

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

Solution 18 - Javascript

To reset/clear all input fields from bootstrap modal use the following code:

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

To hide/close bootstrap modal use the following code:

$('#yourModalId').modal('hide');

Keep Coding 

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionNew to RailsView Question on Stackoverflow
Solution 1 - JavascriptJustinasView Answer on Stackoverflow
Solution 2 - JavascriptVatsal ShahView Answer on Stackoverflow
Solution 3 - JavascripteheydenrView Answer on Stackoverflow
Solution 4 - JavascriptRobView Answer on Stackoverflow
Solution 5 - JavascriptseethaView Answer on Stackoverflow
Solution 6 - Javascriptmusicin3dView Answer on Stackoverflow
Solution 7 - JavascriptShamim HasanView Answer on Stackoverflow
Solution 8 - JavascriptTushar SahaView Answer on Stackoverflow
Solution 9 - JavascriptPiel SilbadView Answer on Stackoverflow
Solution 10 - JavascriptVamshi mylabathulaView Answer on Stackoverflow
Solution 11 - JavascriptJigarb1992View Answer on Stackoverflow
Solution 12 - JavascriptJoão FalcãoView Answer on Stackoverflow
Solution 13 - Javascriptmohamed hajjajView Answer on Stackoverflow
Solution 14 - JavascriptKiran Kumar D MView Answer on Stackoverflow
Solution 15 - JavascriptgiuseppeView Answer on Stackoverflow
Solution 16 - JavascripthaasampathView Answer on Stackoverflow
Solution 17 - JavascriptAnnaView Answer on Stackoverflow
Solution 18 - JavascriptZafar FaheemView Answer on Stackoverflow