Callback function called twice and more on Bootstrap Modal - javascript

I have problem when create custom JQuery plugin that will show Bootstrap modal dialog. The custom plugin require callback function as it's parameter.
The problem are when modal dialog called twice, callback also called twice, and so on.
Here the code:
HTML
test modal
<div class="modal fade" id="general_modal" tabindex="-1" role="dialog" aria-labelledby="general_modalLabel" 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>
<h4 class="modal-title" id="general_modal_title">Set Title Here</h4>
</div>
<div class="modal-body">set modal content here</div>
<div class="modal-footer">
<button type="button" class="btn btn-default close_button" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary action_button">Save changes</button>
</div>
</div>
</div>
Javascript
(function ($) {
$.fn.showDialog = function (options, callback) {
$('#general_modal').modal();
$('#general_modal .action_button').on('click', function () {
callback();
});
}
}(jQuery));
$('.confirm_delete').click(function (e) {
e.preventDefault();
$(this).showDialog(null, function () {
alert('xxx');
});
});
DEMO: http://jsfiddle.net/kJn47/2/

You are rebinding the modal and click events each time showDialog is run. Here's how you might prevent the events being re-attached each time:
(function ($) {
$.fn.showDialog = function (options, callback) {
$('#general_modal').unbind().modal();
$('#general_modal .action_button').unbind().on('click', function () {
callback();
});
}
}(jQuery));
$('.confirm_delete').click(function (e) {
e.preventDefault();
$(this).showDialog(null, function () {
alert('xxx');
});
});

You can call one() against on():
$('#general_modal .action_button').unbind().one('click', function () {
According to documentation:
The .one() method is identical to .on(), except that the handler for a
given element and event type is unbound after its first invocation.
For example:
http://jsfiddle.net/kJn47/47/

Related

bootstrap modal window not closed immediately after 'Yes' button is clicked

I have a bootstrap modal window that I am using in my ASP.NET MVC application.
This modal window is parametrized, I can specify title and message text.
Below is the modal window, MyConfirmModalDialog.cshtml:
<div class="modal fade" id="confirmModalDialog" tabindex="-1" role="dialog" aria-labelledby="modalCenterTitle" aria-hidden="true"
style="padding:0px;margin-left:0px;left:42%;min-width:15%">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="modalTitle">Modal title</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close"
style="margin-top:-30px">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
Modal body
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal" id="confirmCancel">No</button>
<button type="button" class="btn btn-primary" id="confirmOk">Yes</button>
</div>
</div>
</div>
</div>
This modal window is placed within another view using razor helper:
#Html.Partial("MyConfirmModalDialog");
Then I use it like below to show it to the user:
showConfirmation = function (title, message, success, cancel) {
var modal = $("#confirmModalDialog");
modal.find(".modal-title").html(title).end()
.find(".modal-body").html(message).end()
.modal({ backdrop: 'static', keyboard: false });
var fClose = function () {
modal.modal("hide");
};
modal.modal("show");
$("#confirmOk").unbind().one('click', success).one('click', fClose);
$("#confirmCancel").unbind().one("click", fClose);
};
function onPerformActions() {
var title = "Warning";
var message = "Do you wish to continue?";
var success = function () {
performActions();
};
var cancel = function () {
// Do nothing
};
showConfirmation(title, message, success, cancel);
}
If user clicks on 'Yes' button, from success function I call the method peformActions as above code shows. Below method performActions, basically in performs an ajax asynchronous call to an action in the controller:
function performActions()
{
$.ajax({
url: '#Url.Action("DoActions", "MyController", new { area = "MyArea" })',
type: "POST",
async: true,
success: function (resp) {
// Do some things on success
},
error: function () {
// Do some things on error
}
});
}
The problem I have is that modal window is not closed immediately when user clicks on 'Yes' button, it takes some seconds, and then this modal window is overlapped with the next modal window that is shown afterwards in the process.

Binding onclick to element calls the method in jquery

I have a modal:
<div id="myModal" 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">Title</h4>
</div>
<div class="modal-body">
<div>Text</div>
</div>
<div class="modal-footer">
<button type="button" data-dismiss="modal">Cancel</button>
<button id="btn-accept" type="button" data-dismiss="modal">Accept</button>
</div>
</div>
</div>
</div>
I show it from a function in javascript:
function foo(param1, param2){
$("#btn-accept").bind('click', bar(param1, param2)) ;
$("#myModal").modal('show');
}
When I do the binding to the #btn-accept it already calls the method. How can I avoid this?
Wrap it in a function like so:
function foo(param1, param2){
$("#btn-accept").bind('click', function() {
bar(param1, param2);
});
$("#myModal").modal('show');
}
I think you should bind event like this.
function foo(param1, param2){
$("#btn-accept").bind('click', function() {
bar(param1, param2);
});
$("#myModal").modal('show');
}
You can pass data to the event handler:
$( document ).on( 'click', '"#btn-accept"', {'param1' : 'abc', 'param2' : 'cde' }, bar);
Then in your function:
function bar( event ) {
alert( "param1 " + event.data.param1 );
}

Boostrap modal not loading when wired using jquery

I have the following link and I'm trying to load a bootstrap modal when its clicked but the javascript function doesnt seem to be firing. Instead of the view loading inside a modal, its loading as a new page?
#*this is the modal definition*#
<div class="modal hide fade in" id="report-summary">
<div id="report-summary-container"></div>
</div>
<script >
$('a.js-report-summary').click(function (e) {
var url = $(this).attr('href'); // the url to the controller
e.preventDefault();
$.get(url, function (data) {
$('#report-summary-container').html(data);
$('#report-summary').modal('show');
});
});
</script>
public ActionResult ReportSummary()
{
// some actions
return PartialView("ReportSummary", viewmodel)
}
// Report summary view which contains modal
<div class="modal-dialog" role="document">
<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">#ViewBag.FormName - Analysis</h4>
</div>
<div class="modal-body">
...
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary" data-dismiss="modal">
Close</button>
</div>
</div>
</div>
There are no errors showing in the console either so why isn't the jquery function firing?
in your click function, add parameter e this will stand for event
then in the function itself add e.preventDefault() This will stop the refreshing effect.
on your controller method try
public ViewResult ReportSummary()
{
// some actions
if(Request.IsAjaxRequest())
return PartialView("ReportSummary", viewmodel);
else
return View("ReportSummary", viewmodel);
}
on your view
$('#exampleModal').on('show.bs.modal', function (event) {//give your model wrapper an id
//do some ajax and get html
$.ajax({
url:'',
success:function(data){
$('#report-summary-container').html(data);
}
});
})
on your anchor tag, add data-toggle="modal" data-target="#exampleModal"
if you dont want to use bootstrap events trigger your modal with
$('#myModal').modal('show')

Function to append modal

I have 3 modals that all have the same format and are activated by different onclicks (Create Contact, Update Contact, Delete Contact). I am wanting the modal-title and modal-body to change depending on which button was clicked. How would I go about creating a function that appends the modal content depending on which button was clicked? Thank you for your help!
<div id="myModal" class="modal fade">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title">Confirmation</h4>
</div>
<div class="modal-body">
<p>Contact Created!</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">OK</button>
</div>
</div>
</div>
I have written the JavaScript "BootstrapModel" class for the same purpose.
It also depends on jQuery so don't forget to embed jQuery before using this class.
class is :
var BootstrapModal = (function (options) {
var defaults = {
modalId: "#confirmModal",
btnClose: "#btnClose",
title: "Confirm",
content: "Some bootstrap content",
onClose: function () {
},
onSave: function () {
}
};
defaults = options || defaults;
var $modalObj = $(defaults.modalId);
var hideModal = function () {
$modalObj.modal("hide");
};
var showModal = function () {
$modalObj.modal("show");
};
var updateModalTitle = function (title) {
defaults.title = title;
//$($modalObj).find(".modal-title").eq(0).html(title);
$modalObj.find(".modal-title").eq(0).html(title);
};
var updateModalBody = function (content) {
defaults.content = content;
$modalObj.find(".modal-body").eq(0).html(content);
};
return {
getDefaults: function () {
return defaults;
},
hide: function () {
hideModal();
},
show: function () {
showModal();
},
updateTitle: function (title) {
updateModalTitle(title);
return this;
},
updateBody: function (body) {
updateModalBody(body);
return this;
}
}
});
Usage :
var emailModal = new BootstrapModal({modalId: "#confirmModal"});
emailModal.updateTitle("Mail sent successfully").updateBody("<br/>This box will automatically close after 3 seconds.").show();
// Hide the Modal
emailModal.hide();
HTML Structure for the Modal:
<div class="modal fade" id="confirmModal" role="dialog" aria-labelledby="thankyouModal" aria-hidden="true" style="overflow-y: hidden;">
<div class="modal-dialog" style="padding-top: 225px">
<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="thankyouModal">Thank you</h4>
</div>
<div class="modal-body">
Thank you. We'll let you know once we are up.
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
The way I got around this is by loading the data in from external files. So you'd have your initial declaration of your modal box (just the surrounding div), and then in each file you have the containing code for the rest of the modal, then use a bit of jQuery to fire them off:
HTML (in main file)
<div class="modal" id="modal-results" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
</div>
JQuery
$('#create-contact').click(function(){
e.preventDefault();
$("#modal-results").html('create-contact.html');
$("#modal-results").modal('show');
});

What closed the modal?

I am using a twitter bootsrap modal. It contains the buttons "Save", "Cancel" and the arrow for closing. How do handle the case (and recognize it) when the modal is closed by the arrow and when by a button?
$("#myModal).on('hidden.bs.modal', function () {
// ??? Arrow or button is the initiator
});
You need to hook into the button/icon clicks yourself and dismiss the modal from javascript. Here is an example:
$(function () {
var myModal = $("#myModal");
$("#btnShow").on("click", function () {
myModal.modal("show");
});
myModal.find(".closeIcon").on("click", function () {
console.log("Close Icon clicked.");
myModal.trigger("myModal.dismiss.closeIcon");
myModal.modal("hide");
}).end().find(".closeButton").on("click", function () {
console.log("Close Button clicked.");
myModal.trigger("myModal.dismiss.closeButton");
myModal.modal("hide");
}).end().find(".saveButton").on("click", function () {
console.log("Save Button clicked.");
myModal.trigger("myModal.dismiss.saveButton");
myModal.modal("hide");
});
myModal.on("myModal.dismiss.closeIcon", function () {
console.log("Close Icon Handler called.");
}).on("myModal.dismiss.closeButton", function () {
console.log("Close Button Handler called.");
}).on("myModal.dismiss.saveButton", function () {
console.log("Save Button Handler called.");
});
});
Basic Modal HTML (with classes for closeIcon, closeButton, and saveButton added to be able to dispatch the events).
<button id="btnShow">Show Modal</button>
<div id="myModal" class="modal fade">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close closeIcon" aria-hidden="true">×</button>
<h4 class="modal-title">Modal title</h4>
</div>
<div class="modal-body">
<p>One fine body…</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default closeButton" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary saveButton">Save changes</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
jsfiddle here.
Its not possible to track event while closing the modal with data-toggles like data-dismiss="modal".
Try to use the events on each of them to get resolved.

Categories

Resources