[javascript] How to clear all input fields in bootstrap modal when clicking data-dismiss button?

How to clear all input fields in a Bootstrap V3 modal when clicking the data-dismiss button?

This question is related to javascript html twitter-bootstrap

The answer is


Put the contents in your modal inside a form and give it an ID which is equal to "myForm".

When the close button is clicked, give an onclick to the function "myFunction()".

<button class="btn btn-default" data-dismiss="modal" onclick="myFunction()">Cancel</button>

function myFunction() {
            document.getElementById("myForm").reset();
        }

In addition to @Malk, I wanted to clear all fields in the popup, except the hidden fields. To do that just use this:

$('.modal').on('hidden.bs.modal', function () {
    $(this)
        .find("input:not([type=hidden]),textarea,select")
        .val('')
        .end()
        .find("input[type=checkbox], input[type=radio]")
        .prop("checked", "")
        .end();
});

This will clear all fields, except the hidden ones.


There is a more easy and beautiful way:

$('#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 did it in the following way.

  1. Give your form element (which is placed inside the modal) anID.
  2. Assign your data-dimiss an ID.
  3. Call the onclick method when data-dimiss is being clicked.
  4. Use the trigger() function on the form element. I am adding the code example with it.

     $(document).ready(function()
         {
        $('#mod_cls').on('click', function () {
      $('#Q_A').trigger("reset");
        console.log($('#Q_A'));
     })
      });
    

    <div class="modal fade " id="myModal2" role="dialog" >
    <div class="modal-dialog">
    <!-- Modal content-->
    <div class="modal-content">
    <div class="modal-header">
      <button type="button" class="close" ID="mod_cls" data-dismiss="modal">&times;</button>
      <h4 class="modal-title" >Ask a Question</h4>
    </div>
    <div class="modal-body">
      <form role="form" action="" id="Q_A" method="POST">
        <div class="form-group">
          <label for="Question"></label>
          <input type="text" class="form-control" id="question" name="question">
        </div>

      <div class="form-group">
          <label for="sub_name">Subject*</label>
          <input type="text" class="form-control" id="sub_name" NAME="sub_name">
        </div>
        <div class="form-group">
          <label for="chapter_name">Chapter*</label>
          <input type="text" class="form-control" id="chapter_name" NAME="chapter_name">
        </div>
        <button type="submit" class="btn btn-default btn-success btn-block"> Post</button>
                               </form>
    </div>
    <div class="modal-footer">
      <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button><!--initially the visibility of "upload another note" is hidden ,but it becomes visible as soon as one note is uploaded-->
      </div>
      </div>
      </div>
      </div>

Hope this will help others as I was struggling with it since a long time.


This is helpfull, its work for me..

$('.bd-example-modal-sm').on('hidden.bs.modal', function () { 
      $(this).find("select").val('').end(); // Clear dropdown content
      $("ul").empty();   // Clear li content 
});

$('[data-dismiss=modal]').on('click', function (e) 

{

var $t = $(this),

        target = $t[0].href || $t.data("target") || $t.parents('#myModal') || [];

   $(target)

    .find("input")
       .val('')
       .end()
    .find("input[type=checkbox]")
       .prop("checked", " ")
       .end();



$("span.inerror").html(' ');

$("span.inerror").removeClass("inerror");

document.getElementById("errorDiv1").innerHTML=" ";

})      

This code can be used on close(data-dismiss)of modal.(to clear all fields)

  1. Here I have cleared my input fields and my div as id="errorDiv1" which holds all validation errors.

  2. With this code I can also clear other validation errors having class as inerror which is specified in span tag with class inerror and which was not possible using document.getElementsByClassName


The following worked for me:

$(':input').val('');

However, it is submitting the form, so it might not be what you are looking for.


If you are using a form in the modal then you can use

$("#form_id").trigger("reset");

enclose your modal body inside a form with an id="myform"

and then

 $("#activatesimModal").on("hidden.bs.modal",function(){
        myform.reset();
});

should do the trick


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