Clear modal fields after closing modal - javascript

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">
What I want is to clear modal every time its closed so I wrote a script like this:
function clear() {
$("#txtNombreCompleto").val("");
$("#txtNombreEmpresa").val("");
$("#exampleInputEmail2").val("");
$("#dropOficina").val("");
$("#txtTelefono").val("");
$("#txtMensaje").val("");
}
$('#mymodal').on('hidden', function(){
$.clear(this)
});
So my inputs inside the modal are something like this:
<input type="text" class="form-control" id="txtNombreCompleto" name="txtNombreCompleto" placeholder="Nombre completo">
But when I close the modal, it doesn´t run the function, how can I run the function when the modal closes? Regards

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('');
});
});

I tried this code in my project but it didn't work. So I tried this new code
$(document).ready(function() {
$('.modal').on('hidden.bs.modal', function(){
$(this).find('form')[0].reset();
});
});

$('.btnLogMesaj').click(function () { // your button is clicked
$('div#demo').empty(); // clear the "div" of the id "demo"
*
*
*
});
<div class="modal-body">
<div id="demo">
<h4>... Merve's contents </h4>
</div>
</div>

Related

Modal won't close and prevent default on no click, and won't execute func on yes click

I have a modal with two buttons. One is a yes button and one is a no button. If yes button is pressed, I would like the remainder of the function to execute. If no btn clicked, I would like the page to prevent default and not execute. However, it seems that regardless of which button is clicked, nothing happens besides the modal closing. I am using a modal example I found elsewhere, so this may be the issue. After glancing at it for some time I cannot seem to find where the issue is. Am I missing something small? Or perhaps my Jquery is wrong? Below is my code:
Modal:
<!-- Modal for delete-->
<div class="modal fade" id="deleteModal" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content border-primary mb-3 box-shadow-none img-responsive">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="card-body bg-light">
<div id="del" class="center">
<label>Are you sure you want to delete?</label>
</div>
</div>
<div class="modal-footer">
<div id="deleteYes">
<button type="button" class="btn btn-default" data-dismiss="modal" id="deleteYes">Yes</button>
</div>
<div id="deleteNo">
<button type="button" class="btn btn-default" data-dismiss="modal" id="deleteNo">No</button>
</div>
</div>
</div>
</div>
</div>
And here is my Jquery:
$(".btnDeleteTerminalCommand").click(function (e) {
$("#deleteModal").modal('toggle');
if ($("#deleteNo").click) {
return e.preventDefault();
}
var rowId = "#" + $(this).data("rowindex");
var row = $(rowId);
var termId = row.find(".tdTermId").html().trim();
var cmdId = row.find(".tdCmdId").html().trim();
var cmdVal = row.find(".tdCmdVal").html().trim();
var cmdID = row.find(".cmdID").html().trim();
var data = {
TerminalID: termId,
CommandID: cmdId,
CommandValue: cmdVal,
ID: cmdID
};
$.ajax({
url: '#Url.Action("DeleteTerminalCommand", "TerminalCommand")',
type: "POST",
data: data,
success: function (response) {
console.log("Success");
window.location.href = response.Url;
}
});
});
Any advice helps! Thank you!
Your click handler will toggle the modal and immediately continue to execute the rest of the function before the user can click anything. If your modal has two buttons, create a click handler for each button. Perhaps the No button just closes the modal. The Yes button handler can execute the actions required to accomplish the task.
$(".btnDeleteTerminalCommand").click(function(e){
$("#deleteModal").modal('toggle');
}
$("#deleteNo").click(function(e){
$("#deleteModal").modal('hide');
}
$("#deleteYes").click(function(e){
// build data object
// ajax post
}

Invoke Ajax function from Bootstrap modal button

I'm looking to invoke an ajax function after clicking an option from a bootstrap confirmation modal. the confirmation modal will be open through function remove(parameter)
Any help will be appreciated
function remove(parameter){
// $("#remove-modal").modal('show');
/*
if( modal clicked Yes){
..perform ajax call using 'parameter'
}
*/
}
<div class="modal fade" tabindex="-1" role="dialog" aria-labelledby="mySmallModalLabel" aria-hidden="true" id="remove-modal">
<div class="modal-dialog modal-sm">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel">Do you want to remove this item?</h4>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" id="modal-btn-si">Yes</button>
<button type="button" class="btn btn-primary" id="modal-btn-no" data-dismiss="modal">No</button>
</div>
</div>
</div>
</div>
You could just add an event listener for the yes button.
As the event varies every time the modal is shown you remove it before adding the new one.
remove(parameter) {
var yesButton = $("#modal-button-si");
yesButton.off("click");
yesButton.click(function(){
//perform ajax here
});
}
I would assume adding a click handler to the "Yes" button, after the modal is shown, should work. Something like:
function remove(parameter){
// show the dialog
var m = $("#remove-modal").modal('show');
// find the button in your modal, and attach an event
// handler to it's click event
m.on('shown.bs.modal', function(){
m.find('#modal-btn-si').on('click', function(e){
// do something here...
// When you're ready to dismiss the modal, call:
//
// m.modal('hide');
//
// Make sure this is in the callback for your
// AJAX event, unless you want the modal dismissed
// as soon as the button is clicked
});
});
}

Show modal on drop down list selection

I have a modal containing a drop-down list, on selection / the onchange event I would like the new view to be displayed in a modal. I have used this solution for implementing multiple modal overlays and have tried changing the javascript from onclick to on change but there was no luck
My partial view
#using (Html.BeginForm("GameAssignerTable", "Admin", FormMethod.Post, new {role = "form"}))
{
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span></button>
<h3 class="modal-title">Select Investigator Group</h3>
</div>
<div class="modal-body">
#Html.DropDownListFor(m => m.SelectedGroupUserId, Model.GroupList, "Select Investigator Group", new { #class = "form-control modal-link3", onchange = "this.form.submit();" })
</div>
}
My layout page
<div class="container">
<div class="row">
<div id="modal-container3" class="modal fade" tabindex="-1" role="dialog">
<div class="modal-dialog">
<div class="modal-content col-sm-8 col-lg-offset-2">
</div>
</div>
</div>
</div>
</div>
<script type="text/javascript">
$(document).on('show.bs.modal', '.modal', function() {
var zIndex = 1040 + (10 * $('.modal:visible').length);
$(this).css('z-index', zIndex);
setTimeout(function() {
$('.modal-backdrop').not('.modal-stack').css('z-index', zIndex - 1).addClass('modal-stack');
}, 0);
});
// Initialize popover
$(function() {
$('[data-toggle="popover"]').popover({ html: true });
});
// Used for modals
$(function() {
// Initialize modal dialog
// attach modal-container bootstrap attributes to links with .modal-link class.
// when a link is clicked with these attributes, bootstrap will display the href content in a modal dialog.
$('body').on('change', '.modal-link3', function (e) {
e.preventDefault();
$(this).attr('data-target', '#modal-container3');
$(this).attr('data-toggle', 'modal');
});
// Attach listener to .modal-close-btn's so that when the button is pressed the modal dialog disappears
$('body').on('click', '.modal-close-btn', function() {
$('#modal-container').modal('hide');
});
//clear modal cache, so that new content can be loaded
$('#modal-container3').on('hidden.bs.modal', function() {
$(this).removeData('bs.modal');
});
$('#CancelModal').on('click', function() {
return false;
});
});
</script>
I'd recommend pulling the JS out to a handler like the others, and do the following:
$("##Html.IdFor(m => m.SelectedGroupUserId)").on("change", function(e) {
$(this).closest("form").trigger("submit");
});
Note that this submits the form, posting back to the action. That action would then return a view of some sort to show the results. You indicated another modal, but a synchronous postback is going to take you away from your current view.

How clear the previous data while open the bootstrap modal?

Main page contains the google map(div), after selecting state from map, i will try to open bootstrap modal and load the selected county map inside the bootstrap.
Firsttime click Texas state(javascript ShowModalDialog() called) then bootstrap modal alert shows Texas then close.
Second time Ohio is selected, now first alert showing Texas then Ohio.
Why the previous state is showing here?
<script type="text/javascript">
function ShowModalDialog(stateid) {
$('#myModal').modal('show').on('shown.bs.modal', function () {
alert(stateid);
$("#myModal #myModalLabel").html(document.getElementById("statename").value);
var datajson = GetCountyData(stateid);
});
}
</script>
<!-- Modal -->
<div class="modal fade modal-wide" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog" style="color: #808080">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel">Modal title</h4>
</div>
<div class="modal-body">
....
....
..
.
</div>
</div>
</div>
</div>
I think this is bug in bootstrap, because i have several ways to clear modal
$('body').on('hidden.bs.modal', '.modal', function () {
$(this).removeData('bs.modal');
});
But stil got no 'perfect' solutin, becasue with every new call, modal on screen goes a little down, than in firebug i saw there is a lots of modal there just hidden, than i found
http://bootboxjs.com/
And all my problem were solved
$("#myModal").on("hide", function() { // remove the event listeners when the dialog is dismissed
$("#myModal a.btn").off("click");
});
$("#myModal").on("hidden", function() { // remove the actual elements from the DOM when fully hidden
$("#myModal").remove();
});
$("#myModal").modal({ // wire up the actual modal functionality and show the dialog
"backdrop" : "static",
"keyboard" : true,
"show" : true // ensure the modal is shown immediately
});

How to reset the bootstrap modal when it gets closed and open it fresh again?

I have a list box in the bootstrap modal and a button.
When the button is clicked a new button gets rendered inside a div in the modal.
When I close the modal and reopen it, the last operation performed on the modal like the button rendered earlier is still present in the modal.
How do reset the modal so that when the modal is opened again, the button is not present and user can again select the option from the list box and click on the button to render a new button and so on.
<!-- Modal -->
<div
class="modal fade"
id="myModal"
tabindex="-1"
role="dialog"
aria-labelledby="myModalLabel"
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>
<h4 class="modal-title" id="myModalLabel">Select Language</h4>
</div>
<div class="modal-body">
<button type="button" class="btn" data-dismiss="modal">Close</button>
<button type="button" class="btn" id="submit_form">Submit</button>
<div class="modal-body1">
<div id="placeholder-div1"></div>
</div>
</div>
<div class="modal-footer">
<script>
$("#submit_form").on("click", function () {
$(".modal-body1").html("<h3>test</h3>");
});
</script>
<script>
$(function () {
$(".modal-footer").click(function () {
$(".modal").modal("hide");
});
});
</script>
</div>
</div>
</div>
</div>
-- Update ---
Why doesn't this work?
<script type="text/javascript">
$(function () {
$("#myModal").on("hidden.bs.modal", function (e) {
console.log("Modal hidden");
$("#placeholder-div1").html("");
});
});
</script>
Just reset any content manually when modal is hidden:
$(".modal").on("hidden.bs.modal", function(){
$(".modal-body1").html("");
});
There is more events. More about them here
$(document).ready(function() {
$(".modal").on("hidden.bs.modal", function() {
$(".modal-body1").html("Where did he go?!?!?!");
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/js/bootstrap.min.js"></script>
<button type="button" class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal">
Launch modal
</button>
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" 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>
<h4 class="modal-title" id="myModalLabel">Modal title</h4>
</div>
<div class="modal-body">
<div class='modal-body1'>
<h3>Close and open, I will be gone!</h3>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
Tried it and working well
$('#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).
What helped for me, was to put the following line in the ready function:
$(document).ready(function()
{
..
...
// codes works on all bootstrap modal windows in application
$('.modal').on('hidden.bs.modal', function(e)
{
$(this).removeData();
}) ;
...
..
});
When a modal window is closed and opened again, the previous entered and selected values, will be reset to the initial values.
I hope this will help you as well!
Try cloning, then removing and re-adding the element when the modal is hidden. This should keep all events, though I haven't thoroughly tested this with all versions of everything.
var originalModal = $('#myModal').clone();
$(document).on('#myModal', 'hidden.bs.modal', function () {
$('#myModal').remove();
var myClone = originalModal.clone();
$('body').append(myClone);
});
To reset all the input fields in a modal use the following.
$(".modal-body input").val("")
Here's an alternative solution.
If you're doing a lot of changes to the DOM (add/removing elements and classes), there could be several things that need to be "reset." Rather than clearing each element when the modal closes, you could reset the entire modal everytime it's reopened.
Sample code:
(function(){
var template = null
$('.modal').on('show.bs.modal', function (event) {
if (template == null) {
template = $(this).html()
} else {
$(this).html(template)
}
// other initialization here, if you want to
})
})()
You can still write your initial state in HTML without worrying too much about what will happen to it later. You can write your UI JS code without worrying about having to clean up later. Each time the modal is relaunched it will be reset to the exact same state it was in the first time.
Edit: Here's a version that should handle multiple modals (I haven't tested it)...
(function(){
$('.modal').on('show.bs.modal', function (event) {
if (!$(this).data('template')) {
$(this).data('template', $(this).html())
} else {
$(this).html($this.data('template'))
}
// other initialization here, if you want to
})
})()
(function(){
$(".modal").on("hidden.bs.modal", function(){
$(this).removeData();
});
});
This is perfect solution to remove contact while hide/close bootstrap modal.
That's works for me accurately
let template = null;
$('.modal').on('show.bs.modal', function(event) {
template = $(this).html();
});
$('.modal').on('hidden.bs.modal', function(e) {
$(this).html(template);
});
also, you can clone your modal before open ;)
$('#myModal')
.clone()
.modal()
.on('hidden.bs.modal', function(e) {
$(this).remove();
});
Reset form elements ( Works with bootstrap 5 as well). Sample code :
$(document).on("hidden.bs.modal", "#modalid", function () {
$(this).find('#form')[0].reset();
});
you can try this
$('body').on('hidden.bs.modal', '.modal', function () {
$(this).removeData('bs.modal');
});
It will remove all the data from the model and reset it.
I am using BS 3.3.7 and i have a problem when i open a modal then close it, the modal contents keep on the client side no html("") no clear at all. So i used this to remove completely the code inside the modal div.
Well, you may ask why the padding-right code, in chrome for windows when open a modal from another modal and close this second modal the stays with a 17px padding right.
Hope it helps...
$(document)
.on('shown.bs.modal', '.modal', function () {
$(document.body).addClass('modal-open')
})
.on('hidden.bs.modal', '.modal', function () {
$(document.body).removeClass('modal-open')
$(document.body).css("padding-right", "0px");
$(this).removeData('bs.modal').find(".modal-dialog").empty();
})
Sample code:
$(document).on('hide.bs.modal', '#basicModal', function (e) {
$('#basicModal').empty();
});
The below statements show how to open/reopen Modal without using bootstrap.
Add two classes in css
And then use the below jQuery to reopen the modal if it is closed.
.hide_block
{
display:none !important;
}
.display_block
{
display:block !important;
}
$("#Modal").removeClass('hide_block');
$("#Modal").addClass('display_block');
$("Modal").show("slow");
It worked fine for me :)
Using BS 3.3.7
$("#yourModal").on('hidden.bs.modal', function () {
$(this).data('bs.modal', null); // will clear all element inside modal
});
/* this will change the HTML content with the new HTML that you want to update in your modal without too many resets... */
var = ""; //HTML to be changed
$(".classbuttonClicked").click(function() {
$('#ModalDivToChange').html(var);
$('#myModal').modal('show');
});
Reset form inside the modal. Sample Code:
$('#myModal').on('hide.bs.modal', '#myModal', function (e) {
$('#myModal form')[0].reset();
});
To reset/clear all input fields from bootstrap modal use the following code:
$(".modal-body input").val("")
To hide/close bootstrap modal use the following code:
$('#yourModalId').modal('hide');
Keep Coding 😎

Categories