Bootstrap Modal only resets one time
-
23-12-2019 - |
Question
I'm using Bootstrap modal and bootstrap-modal extension with a form inside to do some function on a webpage, and I want to reset that form everytime I close the modal, this is the code I'm using:
<button class="btn <?php if (isset($_SESSION['useremail']) && $_SESSION['useremail'] == ""){ echo 'btn-default btn-sm btn-block';}else{ echo 'btn-primary btn-sm btn-block';}?>" data-toggle="modal" data-target="#chgpwemail_modal" id="mailmanager" <?php if (isset($_SESSION['useremail']) && $_SESSION['useremail'] == "") echo 'disabled="disabled"';?>><i class="fa fa-envelope fa-fw" ></i>Alterar Senha Email</button>
After that the modal is fired and inside it I've got a dismiss button with this code:
$('#dismiss-chgpwemail').click(function(event) {
$('#chgpwemail_modal').modal('hide');
});
$.clearInput = function () {
$('form').find('input[type=text], input[type=password], input[type=number],input[type=email], textarea').val('');
};
$('#chgpwemail_modal').on('hide.bs.modal', function(e) {
$.clearInput();
});
So my problem is following the clearInput() function only functions one time, after its used one time it doesn't work anymore.
And I can't figure out why, since after a complete page reload it does work again!
Solution
If I understand what you are trying to do you can try this. Every time a modal is closed you'll try to find every form inputs and text areas and reset them.
$('#modal').on('hidden.bs.modal', function() {
$('form').find('input').val('');
$('form').find('textarea').html('');
});
Try to reformat the code better. I just noticed that what i typed its the same you have ;)
If you want to register this or every modal in your HTML you can do this: Instead of
$('#modal').on('hidden.bs.modal', function() {
Type this
$('body').on('hidden.bs.modal', '.modal', function () {.....});
With this you'll register the event for every modal you have. Don't forget that ".modal" is the reference for your modals. Replace it with yours.