Converting Bootstrap 3 remote modal to Bootstrap 4 modal with parameters - javascript

So in the near future my shop is going to upgrade to Bootstrap 4 but we cannot do this until we solve the issue with using remote modals. Here is an example of how we load our modals. The reason we use remote modals is because the modal-body is dynamic and may use different file based on the url. I have heard that using jQuery("#newsModal").on("load",..) is an alternative but how could I do this? I found this but I am not sure how my anchor would look and how to build the url to load the remote data.
Global PHP include file:
<div id="NewsModal" class="modal fade" tabindex="-1" role="dialog" data-
ajaxload="true" aria-labelledby="newsLabel" 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 class="newsLabel"></h3>
</div>
<div class="noscroll-modal-body">
<div class="loading">
<span class="caption">Loading...</span>
<img src="/images/loading.gif" alt="loading">
</div>
</div>
<div class="modal-footer caption">
<button class="btn btn-right default modal-close" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
modal_news.php file:
<form id="newsForm">
<div id="hth_err_msg" class="alert alert-danger display-hide col-lg-12 col-md-12 col-sm-12 col-xs-12">
You have some errors. Please check below.
</div>
<div id="hth_ok_msg" class="alert alert-success display-hide col-lg-12 col-md-12 col-sm-12 col-xs-12">
✔ Ready
</div>
<!-- details //-->
</form>
Here is how we trigger the modals :
<a href="#newsModal" id="modal_sbmt" data-toggle="modal" data-target="#newsModal"
onclick="remote='modal_news.php?USER=yardpenalty&PKEY=54&FUNCTION=*GENERAL'; remote_target='#NewsModal .noscroll-modal-body'">
<span class="label label-icon label-info">
<i class="fa fa-bullhorn"></i>
</span>
Promotional Ordering
</a>
I think I need to do something like this when building anchor dynamically:
a) Replace paramters with data-attrs
b) Use the event invoker to get the data-attrs using event.target.id

Thanks to Tieson T. and this post I was able to effectively pass parameters to the remote modal using this technique except if you have multiple modals
I have also included some helpful techniques inside this example as to how you may pass parameters to the remote modal.
bootstrap_modal4.php:
<div class="portlet-body">
Add Attendee <i class="fa fa-plus"></i>
</div>
<!-- BEGIN Food Show Attendee Add/Edit/Delete Modal -->
<div id="attendee" class="modal fade" tabindex="-1" role="dialog" data-ajaxload="true" aria-labelledby="atnLabel" aria-hidden="true">
<form id="signupForm" method="post">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<label id="atnLabel" class="h3"></label><br>
<label id="evtLabel" class="h6"></label>
</div>
<div class="modal-body">
<div class="loading"><span class="caption">Loading...</span><img src="/images/loading.gif" alt="loading"></div>
</div>
<div class="modal-footer">
<span class="caption">
<button type="button" id="add_btn" class="btn btn-success add-attendee hidden">Add Attendee <i class="fa fa-plus"></i></button>
<button type="button" id="edit_btn" class="btn btn-info edit-attendee hidden">Update Attendee <i class="fa fa-save"></i></button>
<button type="button" id="del_btn" class="btn btn-danger edit-attendee hidden">Delete Attendee <i class="fa fa-minus"></i></button>
<button class="btn default modal-close" data-dismiss="modal" aria-hidden="true">Cancel</button>
</span>
</div>
</div>
</div>
</form>
</div>
<script>
jQuery(document).ready(function() {
EventHandlers();
});
function EventHandlers(){
$('#attendee').on('show.bs.modal', function (e) {
e.stopImmediatePropagation();
if($(this).attr('id') === "attendee"){
// Determines modal's data display based on its data-attr
var $invoker = $(e.relatedTarget);
var fscode = $invoker.attr('data-fscode');
console.log(fscode);
// Add Attendee
if($invoker.attr('data-atnid') === "add"){
$("#atnLabel").text("Add New Attendee");
$(".add-attendee").removeClass("hidden");
}
else{ //edit/delete attendee
$("#atnLabel").text("Attendee Maintenance");
$(".edit-attendee").removeClass("hidden");
}
//insert hidden inputs
//add input values for post
var hiddenInput = '<INPUT TYPE=HIDDEN NAME=FSCODE VALUE="' + fscode + '"/>';
$("#signupForm").append(hiddenInput);
}
});
$('#attendee').on('hidden.bs.modal', function (e) {
$(".edit-attendee").addClass("hidden");
$(".add-attendee").addClass("hidden");
$("#signupForm input[type='hidden']").remove();
});
// BOOTSTRAP 4 REMOTE MODAL ALTERNATIVE FOR BOOTSTRAP 3v-
$('#add-attendee').on('click', function(e){
$($(this).data("target")+' .modal-body').load($(this).data("remote"));
$("#attendee").modal('show');
});
}
</script>
bootstrap_remote_modal4.php:
<form id="signupForm">
<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
Hello World!
</div>
</form>
<script>
$(document).ready(function(){
console.log('<?php echo $_GET["USERNAME"]?>'); //passed through url
});
</script>
NOTE: I am having problems with event propagation during the show.bs.modal event which I have a global show.bs.modal that is propagating up to this event handler due to multiple modals so if you have multiple modals make sure to handle them correctly.
Here is a screen shot of the results which clearly show propagation is taking place but the parameter passing techniques are working.

You might find it easier to use something like Bootbox.js, which can be used to dynamically create Bootstrap modals.
Given what you've shown, it would work something like:
trigger modal
with
$(function(){
$('.show-modal').on('click', function(e){
e.preventDefault();
var url = $(this).attr('href');
$.get(url)
.done(function(response, status, jqxhr) {
bootbox.dialog({
title: 'Your Title Here',
message: response
});
});
});
});
This assumes response is an HTML fragment.
Bootbox hasn't officially been confirmed to work with Bootstrap 4, but I haven't run into any problems with it yet (modals seem to be one of the few components that don't have updated markup in BS4).
Disclaimer: I am currently a contributor to Bootbox (mainly updating the documentation and triaging issues).
If you must use only the Bootstrap modal, you're actually after load(). You would probably do something like:
$(function(){
$('.show-modal').on('click', function(e){
e.preventDefault();
var url = $(this).attr('href');
var dialog = $('#NewsModal').clone();
dialog.load(url, function(){
dialog.modal('show');
});
});
});

Related

Javascript not triggering on modal open with Twig Template

Note: I've tried the various solutions found online for my issue, but none of them have worked.
I am trying to pass content from a table where each row has its own button to edit the content in that row. The button opens a Twitter Bootstrap dropdown, which has two buttons, one being the "Edit" button. The edit button opens a modal which has a text-area input. I want the text-area to have the current text present in the table for editing. I am using PHP with Symfony for the forms and Twig for the page rendering.
the button that triggers the modal
<div class="dropdown-menu" aria-labelledby="dropdownMenuButton">
<button class="btn btn-sm dropdown-item edit-button" data-toggle="modal" data-target="#announcementEditModal" data-id="{{ announcement.id }}" data-content="{{ announcement.content }}" type="button">
<div class="announcement-actions">
<span class="fas fa-pencil-alt"></span> Edit announcement
</div>
</button>
The modal
<div class="modal fade" id="announcementEditModal" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-dialog modal-lg" role="document">
<div class="modal-content">
<div class="modal-header announcement-header">
<h5 class="modal-title" id="exampleModalLabel"><span class="fas fa-edit"></span> Edit new announcement</h5>
</div>
<div class="announcement-card-header card m-3 border-0">
<div class="announcement-card-header card-body border-0 p-1">
<span class="fa fa-info-circle fa-lg header-icon"></span>
<h5 class="align-header">ANNOUNCEMENT TEXT</h5>
</div>
<div class="announcement-card-body modal-body card border-0">
{{ form_start(editForm) }}
<div class="announcement-card-body">
<label for="exampleInputEmail1">ANNOUNCEMENT (SUPPORTS MARKDOWN)</label>
<textarea class="form-control" id="announcementText" rows="5" name="content"></textarea>
</div>
</div>
</div>
<div class="card-footer border-0 bg-white pt-0">
<div>
{{ form_widget(editForm.edit, {'left_icon': 'fas fa-check'}) }}
<button type="button" class="btn btn-light" data-dismiss="modal" aria-label="Close">
Cancel
</button>
</div>
</div>
{{ form_end(editForm) }}
</div>
</div>
</div>
The JavaScript
<script type="text/javascript">
$(".edit-button").click(function(){
var content = $(this).data("content");
alert(content);
});
$('#announcementEditModal').on('shown.bs.modal', function () {
alert("modal open");
document.getElementById("#announcementText").val(content);
})
</script>
The alert("modal open") does not fire.I have tried'shown.bs.modal'and'show.bs.modal'`. I'm using Bootstrap 4.12
EDIT: Solution: Once I moved the JS to an announcements.js file where I was doing some stuff with my forms the trigger works.
It appears you either have an incomplete html code or have not shared it all with us.
dropdown-menu does not have a closing div.
wrap dropdown-menu inside dropdown or btn-group.
var content will not be available inside your shown.bs.modal function, so declare it globally, not a very good advice but for simplicity sake.
Fix Javascript error, since you are using jQuery, use it.
document.getElementById("#announcementText").val(content); // val is not function
Replace with
document.getElementById("#announcementText").value = content;
$("#announcementText").val(content); // or jQuery way
And here is the fiddle: https://jsfiddle.net/7onyuw9f/1/
Attempt 2
Below is an example of revealing module pattern to show how you can avoid global variables and also a lot cleaner. You can read more about this pattern here
// Revealing Module Pattern
var MyProject = MyProject || {}; // Your global object
MyProject.Modal = function() { // Namespacing to Modal
var content = ""; // now content is local to this function;
var onEditClick = function() {
$(".edit-button").click(function() {
content = $(this).data("content");
alert(content);
});
};
var onModalShow = function() {
$('#announcementEditModal').on('shown.bs.modal', function() {
alert("modal open");
// $("#announcementText").val(content); <-- jQuery way
document.getElementById("announcementText").value = content;
});
};
var init = function() {
onEditClick();
onModalShow();
};
return {
init: init // expose this for other functions to call
}
}();
$(document).ready(function() {
MyProject.Modal.init();
});
And the fiddle https://jsfiddle.net/x28s3uc9/1/

Bootbox Dialog Modal Bootstrap 4

On my page, I have a table. Inside one of the cells of that table is a link. I am performing jQuery scripts if that link is clicked. For instance if the link is clicked I want to show a Bootstrap Dialog. This can be done easily with Bootbox.js. However, bootbox is not updated with support of Bootstrap 4.
Originally, the bootbox wouldn't even show because in Bootstrap 3, the class name to show something was in, but in Bootstrap 4 it is show. I have fixed that, but here is how it looks currently.
The HTML that is generated by calling bootbox.js for this is:
<div tabindex="-1" class="bootbox modal fade show in" role="dialog" style="display: block;">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button class="bootbox-close-button close" aria-hidden="true" type="button" data-dismiss="modal">×</button>
<h4 class="modal-title">Test Title?</h4>
</div>
<div class="modal-body">
<div class="bootbox-body">Test Message</div>
</div>
<div class="modal-footer">
<button class="btn btn-default" type="button" data-bb-handler="cancel"><i class="fa fa-times"></i> Cancel</button>
<button class="btn btn-primary" type="button" data-bb-handler="confirm"><i class="fa fa-check"></i> Confirm</button>
</div>
</div>
</div>
</div>
The problem is that in the div where the class is modal-header, the button comes before the h4 element. If those were switched, then this problem would be solved, but that is what I need help with. How would I do that via the bootbox syntax? I know I could just remove the title for now until bootbox becomes updated to support bootstrap 4, but I'm curious if this can be done.
Here is what I have so far:
bootbox.confirm({
className: "show", // where I had to manually add the class name
title: "Test Title?",
message: "Test Message",
buttons: {
cancel: {
label: "<i class='fa fa-times'></i> Cancel"
},
confirm: {
label: "<i class='fa fa-check'></i> Confirm"
}
},
callback: function (result) {
// my callback function
}
});
You can just resolve it by css:
.bootbox .modal-header{
display: block;
}
it can be fixed with:
.bootbox .modal-header {
flex-direction: row-reverse;
}
To fix this, you just reverse the positions (in the HTML) of the headline and the x like so:
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
<div tabindex="-1" class="bootbox modal fade show in" role="dialog" style="display: block;">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Test Title?</h4>
<button class="bootbox-close-button close" aria-hidden="true" type="button" data-dismiss="modal">×</button>
</div>
<div class="modal-body">
<div class="bootbox-body">Test Message</div>
</div>
<div class="modal-footer">
<button class="btn btn-default" type="button" data-bb-handler="cancel"><i class="fa fa-times"></i> Cancel</button>
<button class="btn btn-primary" type="button" data-bb-handler="confirm"><i class="fa fa-check"></i> Confirm</button>
</div>
</div>
</div>
</div>
When searching for closeButton here: https://raw.githubusercontent.com/makeusabrew/bootbox/master/bootbox.js things do a little bit hard-coded to me.
However, if you change
dialog.find(".modal-header").prepend(closeButton);
to:
dialog.find(".modal-header").append(closeButton);
in that file, the problem should be fixed.
EDIT:
Actually, there's also dialog.find(".modal-title").html(options.title);
So, you need to append the closeButton to the title. Then it's gonna work as expected.
If people stumble upon this there is a now a version of bootbox 5 which supports bootstrap 4. You can find it here https://www.nuget.org/packages/Bootbox.JS/5.0.0-beta
Perhaps you can re-order the dom in the bootbox callback function, like:
bootbox.confirm({
...
callback: function () {
$('.modal-header').prepend('.modal-title');
}
});
here is what i've done and it worked:
go to your js file (mine is bootbox.min.js), find this line :
var m=b(n.closeButton);a.title?d.find(".modal-header").prepend(m)
and change it for:
var m=b(n.closeButton);a.title?d.find(".modal-header").append(m)
So you just need to change it for "append" and the closebutton should normally be on the right side.

How to properly open and close Bootstrap modal from AngularJS

On my html page, I got just a simple Bootstrap modal and button to call it:
<button class="btn btn-primary" data-toggle="modal" data-target="#addUpdateGroup">Add group</button>
<div class="modal fade" id="addUpdateGroup" tabindex="-1" role="dialog" aria-labelledby="addUpdateGrouplLabel" 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>
</div>
<form name="addUpdateGroupForm" ng-submit="addUpdateGroupForm.$valid && groupCtrl.addUpdateGroup()" novalidate>
<div class="modal-body">
<input type="hidden" ng-model="groupCtrl.group.id" name="groupid" />
<label for="groupname">Group name:</label>
<br>
<input ng-model="groupCtrl.group.name" type="text" name="groupname" id="groupname" required />
<br><br>
<label for="groupcolor">Boja grupe:</label>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-primary">Add</button>
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
</div>
</form>
</div>
</div>
</div>
It's a just simple form. The validation is done by AngularJS.
Now...when user submits the form, I'd like for the modal to close, but ONLY if it was valid input.
So I've put the code for closing the modal into the controller:
this.addUpdateGroup = function() {
// Adding a new group
if (typeof this.group.id === 'undefined') {
this.id += 1;
this.group.id = this.id;
this.groups.push(this.group);
// Updating an existing group
} else {
this.groups[this.group.id].name = this.group.name;
this.groups[this.group.id].color = this.group.color;
}
// Clean the form and remove the modal
this.group = {};
$scope.addUpdateGroupForm.$setPristine(true);
$('.modal').modal('hide');
};
But this doesn't follow the best practice of not manipulating the DOM from the controller.
QUESTION: Is there a better way? How would you implement a modal which needs to be shown or hidden when certain function in controller is called?
You are not following Angular best practices. If you havent done so already, review this legendary answer: https://stackoverflow.com/a/15012542/202913 Specifically points 1 - 3 of that post.
That out of the way, you should be using either of the following two libraries. Both of them implement Bootstrap's functionality, but with a native Angular implementation, i.e. it does not rely on the Javascript library of Bootstrap (but does use the Bootstrap's CSS):
angular-ui/bootstrap
angular-strap
Both are excellent, so use whichever library feels more comfortable to your coding style.

Modal Form Submission without refresh

I have a modal window that pops up when I want to add a new project to my dashboard. I have gotten it to work with jquery post however, I cannot prevent it from refreshing. What I want to do is after the project is added to the database, show a success message and close the modal window after few seconds and not refresh the page (parent page of modal).
Here is my modal
<div class="modal fade" id="add-project-dialog" tabindex="-1" role="dialog" aria-labelledby="basicModal" 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">&times;</button>
<h4 class="modal-title" id="myModalLabel">Add a new Project</h4>
</div>
<div class="modal-body">
<h3>New Project:</h3>
<form class="form-horizontal" id="add-project-form" action="/projects/add" method="POST">
<fieldset>
<!-- Text input-->
<div class="form-group">
<label class="col-md-4 control-label" for="name">Project Name</label>
<div class="col-md-4">
<input id="name" name="name" type="text" placeholder="" class="form-control input-md">
</div>
</div>
<!-- Text input-->
<div class="form-group">
<label class="col-md-4 control-label" for="description">Project Description</label>
<div class="col-md-4">
<input id="description" name="description" type="text" placeholder="" class="form-control input-md">
</div>
</div>
<!-- Text input-->
<div class="form-group">
<label class="col-md-4 control-label" for="project_state">Project State</label>
<div class="col-md-4">
<input id="project_state" name="project_state" type="text" placeholder="" class="form-control input-md">
</div>
</div>
</fieldset>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button id="add-btn" class="btn" type="submit">Add</button>
</div>
</form>
</div>
</div>
Here is my project-dashboard.js
AddProject = function(){
$(document).ready(function() {
$("#submit").submit(function(event){
event.preventDefault();
$.ajax({
url: "/projects/add",
type:"POST",
data:
{
'name': $('#name').val(),
'description': $('#description').val(),
'project_state': $('#project_state').val()
}
});
});
});
}
My views.py
class AddProject(webapp2.RedirectHandler):
def get(self):
template_values = {
#'greetings': greetings,
#'url_linktext': url_linktext,
}
path = os.path.join(os.path.dirname(__file__), '../templates/project-add.html')
self.response.write(template.render(path, template_values))
def post(self):
project = Project()
project.name = self.request.get('name')
project.description = self.request.get('description')
project.project_state = self.request.get('project_state')
time.sleep(2)
project.put()
self.redirect('/projects')
I have tried removing the self.redirect('/projects') however that only takes me to a blank page that is /projects/add (that is the action in the form).
The issue is that you added .ready(foo) handler inside of the AddProject function. I suppose that document is loaded when AddProject is called.
Another issue is that in your HTML, the form has id add-project-form, so you should do $("#add-project-form") instead of $("#submit").
$(document).ready(function () {
$("#add-project-form").submit(function(event){
event.preventDefault();
$.ajax({
url: "/projects/add",
type:"POST",
data:
{
'name': $('#name').val(),
'description': $('#description').val(),
'project_state': $('#project_state').val()
}
});
});
});
});
Take ready handler outside of the AddProject function and it should work (the submit handler is added).
Edit: After some debugging, the answer was to use the right id and proper placing of the javascript code, as noted by the comments.
For starters, a refresh is easy to avoid, just make sure to prevent the default event from running; since you're using jQuery, I would recommend doing return false to end the function, since it both 'prevents default' and 'stops propagation'.
So the first thing you should do is check if your javascript code is actually running and not erring in the middle of execution. If everything is fine there, the worst case is that the project is not actually added (server side error) but the page should not refresh.
Your server side code has nothing to do with the refresh (if it's being properly hijacked), so the response doesn't really matter, I would actually return the id of the new project (so you could provide a link for the newly created item or something like that), but i digress...
Here is a snippet for not only closing modals without page refresh but when pressing enter it submits modal and closes without refresh
I have it set up on my site where I can have multiple modals and some modals process data on submit and some don't. What I do is create a unique ID for each modal that does processing. For example in my webpage:
HTML (modal footer):
<div class="modal-footer form-footer"><br>
<span class="caption">
<button id="PreLoadOrders" class="btn btn-md green btn-right" type="button" disabled>Add to Cart <i class="fa fa-shopping-cart"></i></button>
<button id="ClrHist" class="btn btn-md red btn-right" data-dismiss="modal" data-original-title="" title="Return to Scan Order Entry" type="cancel">Cancel <i class="fa fa-close"></i></a>
</span>
</div>
jQUERY:
$(document).ready(function(){
// Allow enter key to trigger preloadorders form
$(document).keypress(function(e) {
if(e.which == 13) {
e.preventDefault();
if($(".trigger").is(".ok")) //custom validation dont copy
$("#PreLoadOrders").trigger("click");
else
return;
}
});
});
As you can see this submit performs processing which is why I have this jQuery for this modal. Now let's say I have another modal within this webpage but no processing is performed and since one modal is open at a time I put another $(document).ready() in a global php/js script that all pages get and I give the modal's close button a class called: ".modal-close":
HTML:
<div class="modal-footer caption">
<button type="submit" class="modal-close btn default" data-dismiss="modal" aria-hidden="true">Close</button>
</div>
jQuery (include global.inc):
$(document).ready(function(){
// Allow enter key to trigger a particular class button
$(document).keypress(function(e) {
if(e.which == 13) {
if($(".modal").is(":visible")){
$(".modal:visible").find(".modal-close").trigger('click');
}
}
});
});
Now you should get no page refreshes on any of your modals if u follow these steps.

Reload content in modal (twitter bootstrap)

I'm using twitter bootstrap's modal popup.
<div id="myModal" class="modal hide fade in">
<div class="modal-header">
<a class="close" data-dismiss="modal">×</a>
<h3>Header</h3>
</div>
<div class="modal-body"></div>
<div class="modal-footer">
<input type="submit" class="btn btn-success" value="Save"/>
</div>
</div>
I can load content using ajax with this a-element:
<a data-toggle="modal" data-target="#myModal" href="edit.aspx">Open modal</a>
Now I have to open the same modal but using a different url. I'm using this modal to edit an entity from my database. So when I click edit on an entity I need to load the modal with an ID.
<a data-toggle="modal" data-target="#myModal" href="edit.aspx?id=1">Open modal</a>
<a data-toggle="modal" data-target="#myModal" href="edit.aspx?id=2">Open modal</a>
<a data-toggle="modal" data-target="#myModal" href="edit.aspx?id=3">Open modal</a>
If I click on link number 1, it works fine. But if I then click on link number 2 the modal content is already loaded and therefor it will show the content from link number 1.
How can I refresh or reset the ajax loaded content in a twitter bootstrap modal popup?
I guess the way of doing this will be to remove the data-toggle attribute and have a custom handler for the links.
Something in the lines of:
$("a[data-target=#myModal]").click(function(ev) {
ev.preventDefault();
var target = $(this).attr("href");
// load the url and show modal on success
$("#myModal .modal-body").load(target, function() {
$("#myModal").modal("show");
});
});
To unload the data when the modal is closed you can use this with Bootstrap 2.x:
$('#myModal').on('hidden', function() {
$(this).removeData('modal');
});
And in Bootstrap 3 (https://github.com/twbs/bootstrap/pull/7935#issuecomment-18513516):
$(document.body).on('hidden.bs.modal', function () {
$('#myModal').removeData('bs.modal')
});
//Edit SL: more universal
$(document).on('hidden.bs.modal', function (e) {
$(e.target).removeData('bs.modal');
});
You can force Modal to refresh the popup by adding this line at the end of the hide method of the Modal plugin (If you are using bootstrap-transition.js v2.1.1, it should be at line 836)
this.$element.removeData()
Or with an event listener
$('#modal').on('hidden', function() {
$(this).data('modal').$element.removeData();
})
With Bootstrap 3 you can use 'hidden.bs.modal' event handler to delete any modal-related data, forcing the popup to reload next time:
$('#modal').on('hidden.bs.modal', function() {
$(this).removeData('bs.modal');
});
Based on other answers (thanks everyone).
I needed to adjust the code to work, as simply calling .html wiped the whole content out and the modal would not load with any content after i did it. So i simply looked for the content area of the modal and applied the resetting of the HTML there.
$(document).on('hidden.bs.modal', function (e) {
var target = $(e.target);
target.removeData('bs.modal')
.find(".modal-content").html('');
});
Still may go with the accepted answer as i am getting some ugly jump just before the modal loads as the control is with Bootstrap.
A little more compressed than the above accepted example. Grabs the target from the data-target of the current clicked anything with data-toggle=modal on. This makes it so you don't have to know what the id of the target modal is, just reuse the same one! less code = win! You could also modify this to load title, labels and buttons for your modal should you want to.
$("[data-toggle=modal]").click(function(ev) {
ev.preventDefault();
// load the url and show modal on success
$( $(this).attr('data-target') + " .modal-body").load($(this).attr("href"), function() {
$($(this).attr('data-target')).modal("show");
});
});
Example Links:
<a data-toggle="modal" href="/page/api?package=herp" data-target="#modal">click me</a>
<a data-toggle="modal" href="/page/api?package=derp" data-target="#modal">click me2</a>
<a data-toggle="modal" href="/page/api?package=merp" data-target="#modal">click me3</a>
I made a small change to Softlion answer, so all my modals won't refresh on hide.
The modals with data-refresh='true' attribute are only refreshed, others work as usual.
Here is the modified version.
$(document).on('hidden.bs.modal', function (e) {
if ($(e.target).attr('data-refresh') == 'true') {
// Remove modal data
$(e.target).removeData('bs.modal');
// Empty the HTML of modal
$(e.target).html('');
}
});
Now use the attribute as shown below,
<div class="modal fade" data-refresh="true" id="#modal" tabindex="-1" role="dialog" aria-labelledby="#modal-label" aria-hidden="true"></div>
This will make sure only the modals with data-refresh='true' are refreshed. And i'm also resetting the modal html because the old values are shown until new ones get loaded, making html empty fixes that one.
Here is a coffeescript version that worked for me.
$(document).on 'hidden.bs.modal', (e) ->
target = $(e.target)
target.removeData('bs.modal').find(".modal-content").html('')
It will works for all version of twitterbootstrap
Javascript code :
<script type="text/javascript">
/* <![CDATA[ */
(function(){
var bsModal = null;
$("[data-toggle=modal]").click(function(e) {
e.preventDefault();
var trgId = $(this).attr('data-target');
if ( bsModal == null )
bsModal = $(trgId).modal;
$.fn.bsModal = bsModal;
$(trgId + " .modal-body").load($(this).attr("href"));
$(trgId).bsModal('show');
});
})();
/* <![CDATA[ */
</script>
links to modal are
<a data-toggle="modal" data-target="#myModal" href="edit1.aspx">Open modal 1</a>
<a data-toggle="modal" data-target="#myModal" href="edit2.aspx">Open modal 2</a>
<a data-toggle="modal" data-target="#myModal" href="edit3.aspx">Open modal 3</a>
pop up modal
<div id="myModal" class="modal hide fade in">
<div class="modal-header">
<a class="close" data-dismiss="modal">×</a>
<h3>Header</h3>
</div>
<div class="modal-body"></div>
<div class="modal-footer">
<input type="submit" class="btn btn-success" value="Save"/>
</div>
I was also stuck on this problem then I saw that the ids of the modal are the same. You need different ids of modals if you want multiple modals. I used dynamic id. Here is my code in haml:
.modal.hide.fade{"id"=> discount.id,"aria-hidden" => "true", "aria-labelledby" => "myModalLabel", :role => "dialog", :tabindex => "-1"}
you can do this
<div id="<%= some.id %>" class="modal hide fade in">
<div class="modal-header">
<a class="close" data-dismiss="modal">×</a>
<h3>Header</h3>
</div>
<div class="modal-body"></div>
<div class="modal-footer">
<input type="submit" class="btn btn-success" value="Save" />
</div>
</div>
and your links to modal will be
<a data-toggle="modal" data-target="#" href='"#"+<%= some.id %>' >Open modal</a>
<a data-toggle="modal" data-target="#myModal" href='"#"+<%= some.id %>' >Open modal</a>
<a data-toggle="modal" data-target="#myModal" href='"#"+<%= some.id %>' >Open modal</a>
I hope this will work for you.
You can try this:
$('#modal').on('hidden.bs.modal', function() {
$(this).removeData('bs.modal');
});
I wanted the AJAX loaded content removed when the modal closed, so I adjusted the line suggested by others (coffeescript syntax):
$('#my-modal').on 'hidden.bs.modal', (event) ->
$(this).removeData('bs.modal').children().remove()
var $table = $('#myTable2');
$table.bootstrapTable('destroy');
Worked for me
step 1 : Create a wrapper for the modal called clone-modal-wrapper.
step 2 : Create a blank div called modal-wrapper.
Step 3 : Copy the modal element from clone-modal-wrapper to modal-wrapper.
step 4 : Toggle the modal of modal-wrapper.
<a data-toggle="modal" class='my-modal'>Open modal</a>
<div class="clone-modal-wrapper">
<div class='my-modal' class="modal fade">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<a class="close" data-dismiss="modal">×</a>
<h3>Header</h3>
</div>
<div class="modal-body"></div>
<div class="modal-footer">
<input type="submit" class="btn btn-success" value="Save"/>
</div>
</div>
</div>
</div>
</div>
<div class="modal-wrapper"></div>
$("a[data-target=#myModal]").click(function (e) {
e.preventDefault();
$(".modal-wrapper").html($(".clone-modal-wrapper").html());
$('.modal-wrapper').find('.my-modal').modal('toggle');
});

Categories

Resources