js not working in bs3 ajax modal - javascript

I am having some trouble with js inside my bs3 modals - it does not work. I am opening the modals with ajax.
main page
<i class="fa fa-plus-circle"></i> Activate this computer';
<div class="modal fade" id="modal-ajax" tabindex="-1" role="basic" aria-hidden="true">
<img src="/assets/img/ajax-modal-loading.gif" alt="" class="loading">
</div>
<script src="/assets/scripts/custom/custom.js" type="text/javascript"></script>
<script>
jQuery(document).ready(function() {
Custom.init();
});
</script>
custom.js
var Custom = function () {
// private functions & variables
// external window links
var externalWindows = function() {
$("a[data-window='external']").on('click', function() {
window.open($(this).attr('href'));
return false;
});
}
// public functions
return {
//main function
init: function () {
//initialize something here
externalWindows(); // external window links
}
};
}();
the link in the modal page
<a class="btn btn-primary" href="http://www.somesite.com/" data-window="external" onClick="$('#modal-ajax').modal('hide');"><i class="fa fa-shopping-cart"></i> Purchase Now</a>
All this does is open any link with data-window="external" in a new window in the browser. Since the modal page is opened with ajax the js from the main page doesn't 'pick it up' on load. I can add the function on my modal page as well, but then it causes issues with the main page.
What can I do here?

You can use event delegation so that the dynamically loaded links trigger your handler:
var externalWindows = function () {
function openWindow() {
window.open($(this).attr('href'));
return false;
}
$("a[data-window='external").click(openWindow);
$("#modal-ajax").on('click', "a[data-window='external']", openWindow);
};

Related

Modal BootStrap can not get variable asp from codebehind

In MinhasVendas2.aspx :
<div id="myModal" class="modal fade">
<div class="modal-dialog">
<div class="modal-content">
<!-- dialog body -->
<div class="modal-body">
<button type="button" class="close" data-dismiss="modal">×</button>
Forma de Pagamento
<%-- <%# Eval("desc_tp_pagamento") %>
teste--%>
</div>
<div class="modal-body">
Dados Pagto: <%=id_imobiliaria_pagamento%>
<label id="lblteste"></label>
</div>
<!-- dialog buttons -->
<div class="modal-footer"><button type="button" id="a.btn" class="btn btn-primary"data-dismiss="modal">OK</button></div>
</div>
</div>
</div>
<%--#modalformapagto fim--%>
codebehind:
public void gdvPagamentos_SelectIndexChanged(object sender, EventArgs e)
{
try
{
System.Threading.Thread.Sleep(1000);
List<pagamento> pagto = new List<pagamento>();
var id_imobiliaria_pagamento = gdvPagamentos.SelectedRow.Cells[0].Text;
//ClientScript.RegisterClientScriptBlock(this.GetType(), "", "myModal();", true);
ScriptManager.RegisterStartupScript
(Page,
this.GetType(),
"script",
"myModal();",
true);
}
catch(Exception ex){ }
}
Here is the script being triggered via codebehind:
<script type="text/javascript">
function myModal() {
$("#myModal").modal();
$("#myModal").on("show", function () { // wire up the OK button to dismiss the modal when shown
$("#myModal a.btn").on("click", function (e) {
console.log("button pressed"); // just as an example...
$("#myModal").modal('hide'); // dismiss the dialog
});
})
};
function myModalHide() {
$("#myModal").on("hide", function () { // remove the event listeners when the dialog is dismissed
$("#myModal a.btn").off("click");
})
};
function myModalHidden() {
$("#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
})
}
;
</script>
I declare the variable id_imobiliaria_pagamento also outside the method and the data is recovered normal in codebehind.
But this same variable, with the modal open, and called in the html code inside the modal, shows nothing. Can anybody help me?
In the codebehind, inside the method I had declared the variable in a form (example var xxxxx) and out of the method I had defined as string ... with this was occurring the problem of not displaying it ... Strange that did not accuse error . I corrected for tb string inside the method and the contents of the variables came to be displayed.

Handling Errors Within a Modal

I have modal's that are loaded with a link (see below). Whenever there is an error loading the modal (i.e. loading the data in the modal via a wcf service call), there is just a grey screen, as if a modal is trying to open and no modal is loaded. An error is shown in chrome developer tools console which is expected
Additionally, if I click a modal link that loads properly, close that modal, and then click a modal link that generates an error, the previous modal is loaded.
How can I have it so either an error modal is loaded or so a user is redirected to the error page when an error occurs?
Layout (partial view)
<div class="container">
<div class="row">
<div id="modal-container" 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>
// some code here...
$(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);
});
$('body').on('click', '.modal-link', function(e) {
e.preventDefault();
$(this).attr('data-target', '#modal-container');
$(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-container').on('hidden.bs.modal', function() {
$(this).removeData('bs.modal');

Problems with new Google reCAPTCHA in IE when inside modal or dialog

reCAPTCHA works perfectly well in Chrome.
However, (only when reCAPTCHA iframe is inside a dialog box or a modal) in IE the placeholder won't go away.
Whatever the user writes is considered part of the placeholder (I think) and the "verify" button won't be enabled to be clicked.
The picture explains this:
The same code works perfectly well in all browsers when I take the recaptcha div outside the modal
<html lang="en">
<head>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css" rel="stylesheet">
<script src="https://www.google.com/recaptcha/api.js?onload=onloadCallback&render=explicit" async defer></script>
<script src="https://code.jquery.com/jquery-2.1.3.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/js/bootstrap.min.js"></script>
<script type="text/javascript">
var onloadCallback = function() {
grecaptcha.render('html_element', {
'sitekey' : '6Lc7PAATAAAAAE7JwcA7tNEDIrczjCCUvi3GiK4L'
});
};
</script>
</head>
<body>
<div class="container">
<button type="button" class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal">
Launch modal
</button>
<!-- 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">
<form action="?" method="POST">
<div id="html_element"></div>
<br>
<input type="submit" value="Submit">
</form>
</div>
</div>
</div>
</div>
</body>
</html>
The problem is generated by the the modal component of Bootstrap.
When the modal is about to appear this function is called:
Modal.prototype.enforceFocus = function () {
$(document)
.off('focusin.bs.modal') // guard against infinite focus loop
.on('focusin.bs.modal', $.proxy(function (e) {
if (this.$element[0] !== e.target && !this.$element.has(e.target).length) {
this.$element.trigger('focus')
}
}, this))
}
The function adds a "focusin" event to the document to be sure that the focus is still inside the modal; if the focus goes to another element outside the modal then the latter immediately obtain it back.
Therefore, when you click inside the recaptcha form the focus' conflict causes the Internet Explorer bug.
Anyway, one possible solution is to override that method and disable the focus-back behaviour when a recaptcha component obtain the focus, but this is quite difficult to do because there is no control over the recaptcha html (how can you know if e.target is an element of recaptcha?).
My solution is to completely disable this behavior, to do this just override the enforceFocus function with an empty function:
$.fn.modal.Constructor.prototype.enforceFocus = function () { };
A more elegant solution would be apreciated. :)
Old recaptcha, i.e. version 1.0 works ok on the modal
To follow up on the response by 'Digibusiness', A little more elegant would be to override the entire bootstrap function with a practical one (on your page load - the document.ready function would be a good place).
This way, you can refer only to IE when overrding + only to iframes loaded on the modal, hence not screwing accessibility(which have become a big deal these days) all over the site just for a specific iframe-over-modal-on-a-specific-browser functionallity fix.
The code goes follows:
if (window.navigator.userAgent.indexOf("MSIE ") > 0 || !!navigator.userAgent.match(/Trident.*rv\:11\./)) { // If Internet Explorer
$.fn.modal.Constructor.prototype.enforceFocus = function () {
$(document)
.off('focusin.bs.modal') // guard against infinite focus loop
.on('focusin.bs.modal', $.proxy(function (e) {
if (this.$element[0] !== e.target && !this.$element.has(e.target).length) {
if (e.target.nodeName !== "IFRAME") {
this.$element.trigger('focus')
}
}
}, this))
}
}

Bootstrap modal hide is not working

Bootstrap modal hide is not working. Alert comes in else. but my modal is not hidden Added bootply. My issue is the same one.
<button class="button primary" id="buy" data-toggle="modal" data-target=".bs-example-modal-sm" style= "text-decoration:none;" type="button">Review and confirm</button>
<div class="modal-bootstrap fade bs-example-modal-sm" id="myModal" tabindex="-1" role="dialog" aria-labelledby="smallModalLabel" aria-hidden="true">
<div class="modal-bootstrap-dialog modal-sm">
<div class="modal-bootstrap-content">
<div class="modal-bootstrap-body">
-- content ----
</div>
</div>
</div>
<div class="modal-bootstrap-footer">
<button type="submit" class="button primary" data-dismiss="modal">Close</button>
<button type="submit" class="button primary">Save changes</button>
</div>
</div>
<script type="text/javascript">
$("#buy").click(function () {
var a = 4;
if (a == 5) {
alert("if");
$('#myModal').modal('show');
}
else {
alert("else");
$('#myModal').modal('hide');
}
});
</script>
bootply
You are using both modal toggling methods: via Javascript and via data attributes. So your click is firing the modal show as your data attributes set, and your Javascript does not affect this trigger.
Just remove the data attributes and go with the Javascript method:
<button class="button primary" id="buy" style="text-decoration:none;" type="button">Review and confirm</button>
<div class="modal-bootstrap fade bs-example-modal-sm" id="myModal" tabindex="-1" role="dialog" aria-labelledby="smallModalLabel" aria-hidden="true">
<!-- modal contents -->
</div>
<script type="text/javascript">
$("#buy").click(function () {
var a = 4;
if (a == 5) {
alert("if");
$('#myModal').modal('show');
} else {
alert("else");
$('#myModal').modal('hide');
}
});
</script>
I had same problem. Remove fade class.
I had the same problem, tried a lot of things but the only solution that worked for me is #Tang Chanrith suggested to remove individually parts of the modal but a little bit improved to place back and the scrollbar. I'll put my answer just if the accepted answer did not work for them. Sorry for my english. Hope I helped.
#Tang Chanrith
Try this function
function hideModal() {
$("#myModal").removeClass("in");
$(".modal-backdrop").remove();
$("#myModal").hide();
}
Improved Sollution
You just have to delete a class from body and css that generated
function hideModal() {
$("#myModal").removeClass("in");
$(".modal-backdrop").remove();
$('body').removeClass('modal-open');
$('body').css('padding-right', '');
$("#myModal").hide();
}
For those still having issues (hi Googlers!), if you're using fade, you'll have to use javascript to remove fade class.
Try this function
function hideModal(){
$("#myModal").removeClass("in");
$(".modal-backdrop").remove();
$("#myModal").hide();
}
Remove the modal class "fade" will do.
I have solution this problem.
$('#landingpage, body').on('click',function(){
$( ".action-close" ).trigger( "click" );});
try to add return false like this:
$("#buy").click(function () {
var a = 4;
if (a == 5) {
alert("if");
$('#myModal').modal('show');
}
else {
alert("else");
$('#myModal').modal('hide');
}
return false;
});
I checked your code.
Now you compare a == 5. but a is always 4. you may have to check this why you are doing this comparison.
Also you need you remove the data-target if you want to open modal from javascript :
<button class="button primary" id="buy" data-toggle="modal" style="text-decoration:none;" type="button">Review and confirm</button>
data-target directly opening the modal.
Check if this is working.
You should try this $('.modal.in').modal('hide')
Via https://github.com/twbs/bootstrap/issues/489
I had the same problem, my mistake was that I was trying to open the modal window a few times. We must test that the modal window is not already open before trying to open it.
if (!($("#MyModal").data('bs.modal') || {})._isShown){
$("#MyModal").modal('show');
}
Hide modal dialog box using bootstrap
Method 1: using bootstrap
$('.close').click();
$("#MyModal .close").click();
$('#myModalAlert').modal('hide');
Method 2: using stop-propagation
$("a.close").on("click", function(e){
$("#modal").modal("hide");
e.stopPropagation();
});
Method 3: After shown method invoke
$('#myModal').on('shown', function () {
$('#myModal').modal('hide');
})
Method 4: Using CSS
this.display='block'; //Set block css
this.display='none'; //set none css after close dialog
In the java script code you need to add one line of code
$("#savechanges").on("click", function (e) {
$("#userModal").modal("hide");
e.stopPropagation(); //This line would take care of it
});
As I encountered, sometimes you need to remove display style:
style="display: block;"
I had the same issue. I tried the JavaScript way suggested in the post, unfortunately it only worked half of the time. If I triggered my modal a few times, it bugs out. As a result I created a work around using CSS:
/* Hide the back drop*/
.modal-backdrop.show {
display: none;
}
/* Simulate the backdrop using background color */
.modal-open .modal {
background-color: rgba(47, 117, 19, 0.3);
}
I was opening the modal popup when I click on the link using data-toggle="modal" attribute which was bound with that link and trying to close it using javascript but I was failed each time, so when I remove the "data-toggle" attribute and "href" from that link and opened it using javascript then it was closing properly using javascript as well.
from the below few lines of code, you can understand easily
Advanced Search
I changed the above link to something link this
Advanced Search
After that when I try to close it using javascript, then I become successful
$("#CustomerAdvancedModal").modal('hide');
I am also having the same problem, where I can't find the correct solution for it.
Later I observed that what is happening when the modal gets closed when it works well.
Three Main properties are,
modal-open class gets removed from <body> tag.
In <body> tag change CSS .
<div> class of modal-backdrop gets removed.
So, When u do these things manually, you will achieve it, when not works.
The code should be as following in Jquery,
$('body').removeClass('modal-open');
$('body').css('padding-right', '');
$(".modal-backdrop").remove();
$('#myModal').hide();
Hence, try this and get a solution.
Before you open a loading modal, make sure that you close all others.
This is the function is use to close the modal:
function hideLoadingModal() {
$('#loadingModal').on('shown.bs.modal', function () {
$('#loadingModal').modal('hide');
});
}
Now if I want to open the modal I call the above function and open a new one after that.
Like this:
hideLoadingModal();
$('#loadingModal').modal('show');
Hope this helps you.
Cheers
One possible reson should be the order of jquery and bootstrap and your script is not in proper sequence.
Below should be the sequence.
1. <script src='js/jquery-3.2.1.min.js'></script>
2. <script src='js/bootstrap.min.js'></script>
3. your own script:
<script type="text/javascript">
$("#buy").click(function () {
var a = 4;
if (a == 5) {
alert("if");
$('#myModal').modal('show');
}
else {
alert("else");
$('#myModal').modal('hide');
}
});
</script>
Check if you closed all nested div inside main modal div
<div data-backdrop="static" class="modal fade" id="modal-progress" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true">
-----NESTED DIV ------------------
</div>
None of the above solutions worked for me. If this is your case, try to imitate click event on the close button (the one which is added dynamically):
<div class="modal" tabindex="-1" role="dialog" id="modal" area-hidden="true" style="display: inline-block;">
<div class="modal-dialog modal-dialog-centered" role="document">
...
</div>
Close</div>
</div>
$('.close-modal').click() should resolve the issue.
Try this
give an id to close button
<button type="submit" id="modalcloseBtn" class="button primary" data-dismiss="modal" >Close</button>
and trigger onclick event
$('#modalcloseBtn').trigger("click");
G.modals = [];
/**
*
* #param {
* modalId: string,
* callback: function
* } options
* #returns
*/
const openModal = (options) => {
const {
modalId = false,
callback = () => { }
} = options;
if (!modalId) return;
const modalNode = document.querySelector(`#${modalId}`);
modal = new bootstrap.Modal(modalNode);
modal.show();
const modalObject = {
modal,
id: modalId
};
G.modals.push(modalObject);
callback();
};
/**
*
* #param {
* modalId: string,
* callback: function
* } options
* #returns
*/
const closeModal = (options) => {
const {
modalId = false,
callback = () => { }
} = options;
if (!modalId) return;
const currentModal = G.modals.find(item => item.id === modalId) || false;
if(!currentModal) return;
const { modal } = currentModal;
const { _element, _backdrop } = modal;
_element.classList.remove('show');
_backdrop._element.remove();
G.modals.splice(G.modals.indexOf(currentModal), 1);
callback();
};
openModal({
modalId: 'your-modal-id',
callback: () => {
DoSomethingAfterModalOpened();
}
});
closeModal({
modalId: 'your-modal-id',
callback: () => {
DoSomethingAfterModalClosed();
}
});
if nothing helps (that happens) - make sure that nobody prevents it like below (my case):
$modal.on('hide.bs.modal', function (e) {
if (shouldNotBeClosed) {
return e.preventDefault();
}
});
Same issue here for no reason, i'm not using "fade" stuff.
I open modal and close modal only with js, the hide function is working only when called inside a setTimeout.
<script>
var modal_show = function(){
$("#modal_post").modal("show");
};
var modal_hide = function(){
$("#modal_post").modal("hide");
};
window.addEventListener("message", function(event){
// listening iframe post message
modal_hide();
});
</script>
<div class="modal" id="modal_post" tabindex="-1" role="dialog" style="width: 100%;" data-keyboard="false" data-backdrop="static">
<div class="modal-dialog" style="width: 450px; height:600px; background: white; border: none; box-shadow: none;" role="document">
<div class="modal-content" style="width: 100%; background: white; border: none; box-shadow: none;">
<div class="modal-body" style="width: 100%; background: white; border: none; box-shadow: none; padding: 0;">
<div>
<iframe src="https://perdu.com" style="width:450px;height:600px;"></iframe>
</div>
</div>
</div>
</div>
</div>
For no reason, modal_hide(); is working inside the console but not in my code.
If i replace the modal_hide(); in the event listener with setTimeout(modal_hide, 200); it's working properly
its very easy.. Remove fade class :)

bootstrap & javascript: sequence of commands

The following javascript code executes in the following order:
1. shows label,
2. shows alert,
3. shows modal;
but the sequence of the commands in the code is different(see code).
In debug mode execution goes in normal order.
What is happening here?
How to get normal order in runtime?
<html>
<head>
<title></title>
<script src="scripts/jquery-2.0.3.js"></script>
<link href="bootstrap/css/bootstrap.css" rel="stylesheet">
<script src="bootstrap/js/bootstrap.js"></script>
</head>
<body>
<input type="file" onchange="openFile(event)"/>
<div id="myModal" class="modal fade" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">header</div>
<div class="modal-body">body</div>
<div class="modal-footer">footer</div>
</div>
</div>
</div>
<label id="label" style="display:none;">this is label</label>
<script>
openFile = function (event) {
$('#label')[0].style.display = 'block';
$('#myModal').modal('show');
alert('alert');
}
</script>
</body>
</html>
Use callback of model to run something after model is loaded.
openFile = function (event) {
$('#label')[0].style.display = 'block';
$('#myModal').modal('show');
$('#myModal').on('shown', function() {
alert('alert');
})
}
If Bootstrap 3
openFile = function (event) {
$('#label')[0].style.display = 'block';
$('#myModal').modal('show');
$('#myModal').on('show.bs.modal', function() {
alert('alert');
})
}
Try to use deferred objects if you want to make something happen in an explicit order, since jQuery often kicks events asynchrounusly. With deferred objects you can wait for a function to finish, and then define a callback which will be kicked after the said function is done executing.
The Bootstrap .modal() mechanism (like most of the Bootstrap architecture) drives layout changes via events. To show a modal dialog, the code generates a new Event object and triggers it. That's handled asynchronously by the browser, in that the event handler is invoked in a separate (subsequent) event loop.
Here's the first bit of the modal "show" code in the current github master branch:
Modal.prototype.show = function (_relatedTarget) {
var that = this
var e = $.Event('show.bs.modal', { relatedTarget: _relatedTarget })
this.$element.trigger(e)
The handler for that "show.bs.modal" event just adds a class to the <div> involved.

Categories

Resources