John John - 5 months ago 25
Javascript Question

Clear modal fields after close it

I have this modal

<form id="contactModal">
<div id="mymodal2" class="" tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel" 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">×</span><span class="sr-only">Close</span></button>
<span class="modal-title th2" id="lblModalLabel" name="lblModalLabel">Contact</span>
</div>
<div class="modal-body">


That I want is to clear modal every time its closed so I do script like these_:

function clear() {
$("#txtNombreCompleto").val("");
$("#txtNombreEmpresa").val("");
$("#exampleInputEmail2").val("");
$("#dropOficina").val("");
$("#txtTelefono").val("");
$("#txtMensaje").val("");
}
$('#mymodal').on('hidden', function(){
$.clear(this)
});


So my inputs inside modal are something like these:

<input type="text" class="form-control" id="txtNombreCompleto" name="txtNombreCompleto" placeholder="Nombre completo">


But when I close modal, it don´t run function, how can I do to do function when modal closes? Regards

Answer

Simply call clear(); inside bootstrap modal hide.bs.modal event(or hidden.bs.modal) handler or set the function as callback. Also put your code inside document ready handler for attaching event handler after loading the page.

$(document).ready(function() {
  $('#mymodal').on('hidden', function() {
    clear()
  });
});

or get all form all elements inside modal and set value

$(document).ready(function() {
  $('#mymodal').on('hidden', function() {
    $(':input', this).val('');
  });
});