I've been trying to make a lightbox portfolio using the Bootstrap Modal functions, with the quicksand sorting plug-in. I originally followed this tutorial which I had to work with a little to get to work in Bootstrap 3.0.0 (the version I'm using), but it was working. I decided I needed more control over the modal boxes so I took out the bootbox plug-in and just used the modal js that comes in bootstrap. Now when I press the thumbnail the modal box pops up fine, but if I press one of the sorting nav buttons, the box will pop up with either the last image that was in the modal (not the correct one) or if the first thing you do is sort then click, the modal box pops up but it is empty. The tutorial mentioned the problem and a work-around:
"Inherently, Quicksand will nullify Bootstrap’s modal feature as soon
as you interact with any of the categories. That is, the modal works
before firing Quicksand, but not after. However, we’ve easily avoided
this issue by defining our Bootbox function earlier. As shown above,
we then used “gallery” as an attribute inside the quicksand() function
and setup $(document).ready(gallery);. Now modal will work as expected
both before and after selecting a filter/category."
but it doesn't seem to work with the normal bootstrap modal. The only similar question I could find is this one, the answer was to add a call-back, since the objects sorted by quicksand are actually new objects that have not been affected by the modal script, but when I added the callback it didn't work.
here is my code (I left out all the other thumbnails)
<div class="container well well-lg">
<ul class="filter nav nav-pills">
<li data-value="all"><h6>All</h6></li>
<li data-value="Historical"><h6>Historical</h6></li>
...
</ul>
<hr>
<ul class="thumbnails">
<li class="col-lg-2 col-md-2 col-sm-3 col-xs-4" data-id="id-1" data-type="Historical">
<a class="thumbnail" data-toggle="modal" data-target="#myModal" id="joan1" href="#" data-image-id="" data-title="Joan of Arc" data-caption="Digital, Junior Thesis subject Crime and Punishment, 2015" data-image="/images/joan1.png">
<img alt="" src="/images/thumb_joan1.png"></a>
</li>
...
</ul>
</div>
<!-- Modal -->
<div class="modal modal-wide fade" id="myModal" role="dialog">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h3 class="modal-title" id="myModal-title"></h3>
</div>
<div class="modal-body">
<img id="myModal-image" class="img-responsive" src="">
</div>
<div class="modal-footer">
<div class="col-md-2">
<button type="button" class="btn btn-primary" id="show-previous-image">Previous</button>
</div>
<div class="col-md-8 text-justify" id="myModal-caption">
</div>
<div class="col-md-2">
<button type="button" id="show-next-image" class="btn btn-default">Next</button>
</div>
</div>
</div>
</div>
</div>
and here is my javascript
<script src="/Scripts/jquery.quicksand.js" type="text/javascript"></script>
<script>
$(document).ready(function () {
loadGallery(true, 'a.thumbnail');
$(".modal-wide").on("show.bs.modal", function () {
var height = $(window).height() - 200;
$(this).find(".modal-body").css("max-height", height);
});
function disableButtons(counter_max, counter_current) {
$('#show-previous-image, #show-next-image').show();
if (counter_max == counter_current) {
$('#show-next-image').hide();
} else if (counter_current == 1) {
$('#show-previous-image').hide();
}
}
function loadGallery(setIDs, setClickAttr) {
var current_image,
selector,
counter = 0;
$('#show-next-image, #show-previous-image').click(function () {
if ($(this).attr('id') == 'show-previous-image') {
current_image--;
} else {
current_image++;
}
selector = $('[data-image-id="' + current_image + '"]');
updateGallery(selector);
});
function updateGallery(selector) {
var $sel = selector;
current_image = $sel.data('image-id');
$('#myModal-caption').text($sel.data('caption'));
$('#myModal-title').text($sel.data('title'));
$('#myModal-image').attr('src', $sel.data('image'));
disableButtons(counter, $sel.data('image-id'));
}
if (setIDs == true) {
$('[data-image-id]').each(function () {
counter++;
$(this).attr('data-image-id', counter);
});
}
$(setClickAttr).on('click', function () {
updateGallery($(this));
});
};
function gallery() {
}
var $itemsHolder = $('ul.thumbnails');
var $itemsClone = $itemsHolder.clone();
var $filterClass = "";
$('ul.filter li').click(function (e) {
e.preventDefault();
$filterClass = $(this).attr('data-value');
if ($filterClass == 'all') { var $filters = $itemsClone.find('li'); }
else { var $filters = $itemsClone.find('li[data-type=' + $filterClass + ']'); }
$itemsHolder.quicksand(
$filters,
{ duration: 1000 },
loadGallery
);
});
});
$holder.quicksand($filteredData, {
duration: 800,
easing: 'easeInOutQuad'
}, gallery);
$(document).ready(gallery);
</script>
and here is the live page where you can see the problem. I'm pretty new to this so hopefully I just messed up something basic and fixable. Thanks in advance for any help!
Hi your thumbnail click event does not trigger after filtering, when filtering you are creating a clone of the elements and adding them to back to the DOM, Therefore your trying to bind a click event to elements that are not on the page yet, to fix bind to an element that's is always on the page, then use your variable 'setClickAttr' for the Selector filter
i.e change
$(setClickAttr).on('click', function () {
....
});
to
$(document).on('click', setClickAttr, function() {
....
});
This Turning live() into on() in jQuery talks more about binding to elements that must exist first
Related
I'm trying to load map in bootstrap modal but map appear partly, it's also freezing so I can't select any region. Despite of using map.invalidateSize() my problem is still resisting. Is there anybody to make it work in bootstrap modal or any other kind of modal?
here is my code:
<script type="text/javascript">
var LbsConfig = {
Url:'https://map.ghasedakbahar.ir:6443/arcgis/rest/services/iran/FeatureServer/0',
View: [35.6970, 51.4079],
MapID: 'map-id',
Color: {
Default: '#9ab9ff',
Selected: '#ff0659'
}
};
var map = LbsMap();
LbsShowNew(map, function (regions) {
var maxRegions = 5;
var errRegions = 'The number of areas is more than 5 areas';
if (regions.length > maxRegions) {
alert(errRegions);
return;
}
jQuery('#Regions').val(regions.join(','));
jQuery('#count-selected').html(regions.length);
});
$('#myMap').on('show.bs.modal', function () {
setTimeout(function () {
map.invalidateSize();
}, 10);
});
</script>
#map-id {
padding: 0;
width: auto;
height: 400px;
}
<!-- Modal -->
<div class="modal fade" id="myMap" role="dialog" style="margin-top:70px">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content font-yekan">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">'SendSmsDetail'</h4>
</div>
<div class="modal-body" id="modal-body">
<div id="map-id"></div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
I remember having the same problem before. There is a lot of similar problem on internet and maybe this one can help you :
Leaflet map not showing properly in bootstrap 3.0 modal
I think what is happening is that, when the map is created, the
container width/height for your `map-canvas' element has not yet been
adjusted to the width/height of the modal dialog. This causes the map
size to be incorrect (smaller) than what it should be.
You can fix this by calling map.invalidateSize(). This will work to
re-adjust the width/height bounds of the L.Map's container.
You can automatically call this by hooking into the event where the
Bootstrap modal becomes shown.
$('#myModal').on('show.bs.modal', function(){
setTimeout(function() {
map.invalidateSize();
}, 10);
});
Insert this code into your JavaScript. When the modal is shown, the
map will then invalidate its size. The timeout is because there may be
some animation/transition time for the modal to display and be added
to the DOM.
I am trying to figure out why this particular Bootstrap confirmation modal is not working with my desired function. It does appear to work with a basic function bringing up an alert window but when I put the function I want it, it executes the function (in this case deletes an image from File-stack and my db) but it hangs up the modal window to where the modal window closes but there is that grey overlay stuck and it makes the page no longer functional. The function that seems to be holding this up is in the first button in the modal-footerdiv towards the bottom. The close button works fine and again it works fine when I put a simple function in place of the removeMoreImage() function Here is the code for the Bootstrap modal:
<button type="button" class="btn btn-danger" data-toggle="modal" data-target="#confirm-modal-more"> <span class= "glyphicon glyphicon-remove-circle"></span> REMOVE IMAGE</button>
<div id="confirm-modal-more" class="modal fade" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Remove Image Confirmation</h4>
</div>
<div class="modal-body">
<p>Are you sure you want to delete this image?</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-danger" data-ng-click="removeMoreImage(picture.url, car)" data-dismiss="modal" >REMOVE</button>
<button type="button" class="btn btn-default" data-dismiss="modal">CANCEL</button>
</div>
</div>
</div>
</div>
Here is the function that is is executing causing the hangup:
var getIndexIfObjWithOwnAttr = function(array, attr, value) {
for (var i = 0; i < array.length; i++) {
if (array[i].hasOwnProperty(attr) && array[i][attr] === value) {
return i;
}
}
return -1;
}
$scope.removeMoreImage = function(image, data) {
var index = getIndexIfObjWithOwnAttr(data.morePictures, 'url', image);
data.morePictures.splice(index, 1);
filepickerService.remove(image);
console.log(image + " has been removed!");
}
Any insights or advice would be great. It seems like sync issue but I am not sure.
I ended up using some query to force the modal close and it seems to work nicely though it is not as elegant of a solution as I was hoping for but it seems to work. This is the code I added to the function that was hanging up the modal.
$('#confirm-modal-more').modal('hide');
$('body').removeClass('modal-open');
$('.modal-backdrop').remove();
You can close the modal in the function and return a result to the parent controller:
$uibModalInstance.close('some result of modal');
$uibModalInstance.dismiss('some reason for discarding and closing');
$scope.removeMoreImage = function(image, data) {
var index = getIndexIfObjWithOwnAttr(data.morePictures, 'url', image);
data.morePictures.splice(index, 1);
filepickerService.remove(image);
console.log(image + " has been removed!");
// close modal
$uibModalInstance.close();
}
https://angular-ui.github.io/bootstrap/#/modal
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.
Not sure if this is possible, I'm just starting to learn javascript and jQuery. If the way that I would like is not possible, I am very open to hearing of different ways I may be able to achieve this.
I want to display a datepicker, the user will click on dates and when they do a dialog box appears which has specific predefined data in it. They can select a different date, and it will open another dialog box with different predefined data in it, and I want to keep track of the dates that they click on.
<div id="tabs">
<ul>
<li>First</li>
<li>Second</li>
<li>Third</li>
</ul>
<div id="tabs-1">
<p>I'm going to have different data applying to only this day</p>
</div>
<div id="tabs-2">
<p>I'm going to have different data applying to only this day</p>
</div>
<div id="tabs-3">
<p>I'm going to have different data applying to only this day</p>
</div>
</div>
Open jQuery dialog box upon selecting a date from jQuery datepicker inline
That link was useful because a user has a jsfiddle posted: http://jsfiddle.net/qqabC/ which is a start to what I am trying to do, I am just not sure of how or if it is even possible to incorporate divs into the dialog boxes like so. I keep messing around with it but I have been getting nowhere. Each date that is selected will have different dialog box content in it.
If this is not possible, what would be the best way to achieve this? Thank you.
--Edit:
I still need to implement the divs that I have defined above with div id "tabs". Tabs = workout days. So tabs-1 to tabs-5 would be 5 total days. tabs-1 is going to be their first click which is day 1 form content, tabs-2 will be their second click which is day 2 form content, and so on. I believe I should use a for loop, because which each click the div is being incremented onto the next one. I was trying to do something like:
var divs = $('#tabs > div[id]');
var links = $('#tabs li');
divs.hide();
for (i=0;i<=max_workouts;i++) {
$('#tabs li').on('click', function(e){
var clickedID = $(this).attr('href').clone().appendTo(#workout-modal);
}
Something like that, to iterate through the div's with each click, but it's not working, I have been trying to find examples of placing existing div content in modals but there is nothing on iterating through divs in this way, do you have any suggestions?
Here is an example of how you could achieve this functionality using Bootstrap. Of course you'll need to change the functionality and design as needed but this should be a fair start
The workflow is as follows:
User clicks a date
Modal is displayed with various inputs
Inputs are cleared when modal opens
User enters info in the inputs
User clicks add workout
A span label is added to the display showing the workout number and the date selected
This span has data attributes set to store the date, title, and each of the values from the modal inputs
If user clicks the "X" on the right end of the span, it is removed
If user clicks the span label anywhere else it reopens the modal and populates the inputs with the data stored as attributes on the span
If the user clicks add workout after loading an existing one, the new span replaces the old one instead of adding to the end of the div
Here is a jsFiddle also
$(function(){
var max_workouts = 5;
$('#workout-datepicker').datepicker({
startDate: "today"
}).on('changeDate', function(e) {
var cur = $('.workout-label').length;
if (cur < max_workouts) {
var workoutDate = e.format('mm/dd/yyyy');
var title = 'Workout ' + (cur + 1) + ' - ' + workoutDate;
openModal(title, workoutDate);
}
else{
var $tooMany=$('#too-many');
$tooMany.show();
setTimeout(function(){ $tooMany.hide() }, 2000);
}
});
var $workoutLabelsContainer = $('#workout-labels-container');
$('#add-workout').click(function() {
var $workoutModal = $('#workout-modal');
var workoutDate = $workoutModal.data('workout-date');
var title = $workoutModal.data('workout-title');
var vaule1 = $('#modal-workout-value-1').val();
var vaule2 = $('#modal-workout-value-2').val();
var $workout = $('<span class="label label-primary workout-label col-sm-12">' + title + '<span class="glyphicon glyphicon-remove pull-right remove-workout" aria-hidden="true"></span></span>');
var clickedLabelIndex = $workoutModal.data('crurent-label-index');
$workout.data('workout-title', title).data('workout-date', workoutDate).data('value-1', vaule1).data('value-2', vaule2);
if (clickedLabelIndex == -1) $workoutLabelsContainer.append($workout);
else($('.workout-label').eq(clickedLabelIndex).replaceWith($workout))
$workoutModal.modal('hide');
});
$workoutLabelsContainer.on('click', '.remove-workout', function(e) {
e.stopPropagation();
$(this).closest('.workout-label').remove();
})
$workoutLabelsContainer.on('click', '.workout-label', function() {
var $workoutLabel = $(this);
var workoutDate = $workoutLabel.data('workout-date');
var title = $workoutLabel.data('workout-title');
var value1 = $workoutLabel.data('value-1');
var value2 = $workoutLabel.data('value-2');
var labelIndex = $('.workout-label').index($workoutLabel);
openModal(title, workoutDate, value1, value2, labelIndex);
});
function openModal(title, workoutDate, value1, value2, labelIndex) {
var $workoutModal = $('#workout-modal');
var $value1 = $('#modal-workout-value-1').val('');
var $value2 = $('#modal-workout-value-2').val('');
$workoutModal.data('workout-title', title).data('workout-date', workoutDate);
$('#workout-modal-title').html(title);
if (value1) $value1.val(value1);
if (value2) $value2.val(value2);
if (labelIndex !== 'undefined' && labelIndex > -1) $workoutModal.data('crurent-label-index', labelIndex);
else $workoutModal.data('crurent-label-index', -1);
$workoutModal.modal({
show: true
});
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.5.1/js/bootstrap-datepicker.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.5.1/css/bootstrap-datepicker.min.css" rel="stylesheet"/>
<link href="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js"></script>
<style>
.workout-label {
padding: 6px;
font-size: 16px;
width: 100%;
display: block;
margin-bottom: 5px;
cursor: pointer;
}
.remove-workout {
cursor: pointer;
}
#too-many{
display:none;
}
</style>
<br>
<br>
<div class="container well" id="workout-container">
<div class="row">
<div class="col-xs-6">
<div id="workout-datepicker"></div>
</div>
<div class="col-xs-6" id="workout-labels-container">
</div>
</div>
<div class="alert alert-danger" id="too-many" role="alert">Maximun reached</div>
</div>
<div id="workout-modal" class="modal fade" 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" aria-hidden="true">×</button>
<h3 id="workout-modal-title"></h3>
</div>
<div class="modal-body">
<form class="form-horizontal" role="form">
<div class="form-group">
<label for="firstname" class="col-sm-4 control-label">Some short text:</label>
<div class="col-sm-8">
<input type="text" class="form-control" id="modal-workout-value-1" placeholder="">
</div>
</div>
<div class="form-group">
<label for="lastname" class="col-sm-4 control-label">Some longer text:</label>
<div class="col-sm-8">
<textarea class="form-control" id="modal-workout-value-2" name="textarea"></textarea>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn" data-dismiss="modal" aria-hidden="true">Cancel</button>
<button type="button" class="btn btn-primary" id="add-workout">Add workout</button>
</div>
</form>
</div>
</div>
</div>
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 😎