49

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

Rob Lyndon
  • 12,089
  • 5
  • 49
  • 74
EgyEast
  • 1,542
  • 6
  • 28
  • 44

10 Answers10

96

http://getbootstrap.com/javascript/#modals shows an event for when a modal is hidden. Just tap into that:

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

http://jsfiddle.net/5LCSU/


I would suggest the above as it bind the clearing to the modal itself instead of the close button, but I realize this does not address your specific question. You could use the same clearing logic bound to the dismiss buttons:

$('[data-dismiss=modal]').on('click', function (e) {
    var $t = $(this),
        target = $t[0].href || $t.data("target") || $t.parents('.modal') || [];

  $(target)
    .find("input,textarea,select")
       .val('')
       .end()
    .find("input[type=checkbox], input[type=radio]")
       .prop("checked", "")
       .end();
})

http://jsfiddle.net/jFyH2/

Malk
  • 11,855
  • 4
  • 33
  • 32
  • Thanks for answer but this only works for me when i hide modal using $('#myModal').modal('hide') but when using data-dismiss="modal" this event is not fired – EgyEast Jan 17 '14 at 00:17
  • 2
    My input clearing code was not quite right and would have thrown an error if used verbatim. I cleaned it up. I also added a fiddle link, the form fields seem to clear out just fine when the dismiss button is clicked. Maybe you can adjust the fiddle to replicate your use case and we can take a better look. – Malk Jan 17 '14 at 17:14
  • It also clears the button labels of my input type submit. Better do: .find("input[type=email],input[type=text],textarea,select") – metamagikum May 20 '17 at 11:35
  • $("#formID").validate().resetForm(); will also reset the form jquery javascript validation. – Abdush Samad Miah Aug 19 '17 at 20:46
  • is there a way not affecting the input button? – natsumiyu Nov 13 '18 at 06:08
  • You can change the input select to filter out button type: `.find("input,textarea,select")` => `.find("input:not([type=button]),textarea,select")`, but you should look into resetting the form as suggested in another answer first and come back to this approach if you need more granular control. – Malk Nov 13 '18 at 18:50
79

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

Mithril
  • 12,947
  • 18
  • 102
  • 153
9

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

$("#form_id").trigger("reset");
Hp Sharma
  • 309
  • 3
  • 7
4

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.

neophyte
  • 6,540
  • 2
  • 28
  • 43
2

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();
        }
Sidharth
  • 21
  • 1
1
$('[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

AdrienW
  • 3,092
  • 6
  • 29
  • 59
harshada
  • 11
  • 1
1

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 
});
Viral M
  • 261
  • 2
  • 14
1

The following worked for me:

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

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

Alex P.
  • 1,140
  • 13
  • 27
1

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.

MrG
  • 372
  • 2
  • 13
0

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

ShAkKiR
  • 863
  • 9
  • 20