Search code examples
twitter-bootstrapmodal-dialogbootstrap-modal

bootstrap modal get to initial UI state after close


I am using a Bootstrap 3 modal. I have a text input inside the modal and a link when clicked will create new text input fields below the first one to a maximum of 4 fields. My code works fine and it creates more input fields.

But, when I close the modal and open it again there are more than one input text field depending on the number of times I clicked the link previously. I don't want this to happen - when I close the modal and open it again I would like to see only one input text field (initial state) and not see the changes to the DOM in the modal. Is this possible?

Link to my code


Solution

  • You want to use the hide.bs.modal event based on the BOotstrap Javascript documentation here

    First I would add a class to all the input elements and newly rendered div elements clearAfterClose for inputs and hideAfterClose for divelements. Then I would create my Jquery function as:

    $('#myModal').on('hide.bs.modal', function(e) {
      $('.clearAfterClose').val('');
      $('.hideAfterClose').hide();
    }) 
    

    This will fire whenever the modal is hidden and clear all input elements with the the clas clearAfterClose and hide all divs with the clas hideAfterClose. I created a codepen for demonstration here