how re-use bootstrap modal dialog with multiple links - javascript

I am trying to re-use a bootstrap modal with this jsFiddle found http://jsfiddle.net/jhfrench/qv5u5/51/. The problem I am having is I have to refresh the page before being able to use another link. Otherwise the url from first link selected is shown when another link is selected. Can anyone see where I am going wrong?
Below is what I have.
( I apologise if I haven't done this correctly as this is my first post )
<script> $('a[data-toggle="modal"]').on('click', function(){
// update modal header with contents of button that invoked the modal
$('#myModalLabel').html( $(this).html() );
//fixes a bootstrap bug that prevents a modal from being reused
$('#utility_body').load(
$(this).attr('href'),
function(response, status, xhr) {
if (status === 'error') {
//console.log('got here');
$('#utility_body').html('<h2>Oh boy</h2><p>Sorry, but there was an error:' + xhr.status + ' ' + xhr.statusText+ '</p>');
}
return this;
}
);
});
</script>
<div id="utility" class="modal hide fade" tabindex="-1" role="dialog" aria- labelledby="myModalLabel" aria-hidden="true">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h1 id="myModalLabel">The Right to Manage Process</h1>
</div>
<div class="modal-body" id="utility_body">
<p>One fine body…this is getting replaced with content that comes from passed-in href</p>
</div>
<div class="modal-footer">
<button class="btn" data-dismiss="modal">Close</button>
<button class="btn btn-primary">Save changes</button>
</div>
</div>
<ul>
<li><a data-target="#utility" href="retirement-modal-content/rtm-process.html" role="button" data-toggle="modal">The Right to Manage Process</a></li>
<li><a data-target="#utility" href="retirement-modal-content/mgmt-sel-prcs.html" role="button" data-toggle="modal">The Management Selection Process</a></li>
</ul>

Related

How to toogle different modal with different content and change the button as well?

I wanna toggle different models and calculate the results in form individually.
I try to avoid paste too many modal codes and found the sample HERE, however, it use the same ID, so I get stuck!
If you click on
Button A it shows Modal A with Calculate A.
Button B it shows modal B with Calculate B.
Button N it shows modal N with Calculate N.
Is there a way to change the button to another one? or any help?
Much appreciate!
$('#exampleModal').on('show.bs.modal', function(event) {
var button = $(event.relatedTarget) // Button that triggered the modal
var recipient = button.data('whatever') // Extract info from data-* attributes
// If necessary, you could initiate an AJAX request here (and then do the updating in a callback).
// Update the modal's content. We'll use jQuery here, but you could use a data binding library or other methods instead.
var modal = $(this)
modal.find('.modal-title').text('Form click on ' + recipient)
modal.find('.modal-body input').val(recipient)
$("#buttonA").click(function () {
var a = $("#amout").val();
alert("Results: " + a);
});
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"></script>
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal" data-whatever="button A">Run button A</button>
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal" data-whatever="button B">Run button B</button>
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal" data-whatever="button N">Run button ...N</button>
<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Form 1-N</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<form>
Num: <input id="amout" type="number">
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary" id="buttonA">calculate</button>
</div>
</div>
</div>
</div>
The Fastest way is set id for each button you want change and Change innerText of that in your Function.
Html Tag
<button id="AcceptBTN" type="button" class="btn btn-primary">Send message</button>
^
|
Here
jQuery
$('#exampleModal').on('show.bs.modal', function(event) {
var button = $(event.relatedTarget) // Button that triggered the modal
var recipient = button.data('whatever')
// Extract info from data-* attributes
// If necessary, you could initiate an AJAX request here (and then do the updating in a callback).
// Update the modal's content. We'll use jQuery here, but you could use a data binding library or other methods instead.
$('#AcceptBTN')[0].innerText = recipient; <-----------------Here
var modal = $(this)
modal.find('.modal-title').text('New message to ' + recipient)
modal.find('.modal-body input').val(recipient)
})
GoodLuck

Bootstrap / Modal alert - log shows with no alert

Basically, the extension I am working on is supposed to show an alert box when clicked. However the button does it's job by going to the next step "skipping verification" without showing the box as it should.
When the button is clicked, I receiving this back from the console.
$("#usps_skip").click(function() {
console.log("skipCLicked");
var msg = "No address information will be stored with the Contact record if you skip USPS verification. Do you still wish to skip the USPS verification step?";
$('#errorModal .modal-body').html(msg.split('\n').join('<br />'));
$('#errorModal').modal('show');
});
The "skipCLicked" log is showing up in the console, but the actual modal message alert is not appearing. Any suggestions?
Below is my code in the chrome extension.
js code
switch(ObjField.id)
{
//other case code removed since it is not necessary
case "usps_skip":
str_field = str_field + '<button class="btn btn-danger" data-target="#errorModal" name="'+ObjField.name+'" id="'+ObjField.id+'" value="">'+ObjField.label+'</button>';
//str_field = str_field + '<button type="button" class="btn btn-danger" data-toggle="modal" data-target="#errorModal" name="'+ObjField.name+'" id="'+ObjField.id+'" value="">'+ObjField.label+'</button>';
break;
modal / tabs.htm
<div id="errorModal" class="modal fade" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title">Error</h4>
</div>
<div class="modal-body">
<p></p>
</div>
<div class="modal-footer">
<button type="button" id="modalSkip" class="btn btn-success" data-dismiss="modal">Skip Verification</button>
<button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
The button works as it should but no message shows, any help would be appreciated.
Edit: console.log("skipCLicked"); is shown via console, so it works up to that point.
Did You try:
$('#myModal').on('shown.bs.modal', function (e) {
console.log('is modal open?'); // does it shown in console? if not then modal is not open.
// do something... like $('#errorModal .modal-body').html(msg.split('\n').join('<br />'));
});
Ps. if console.log('is modal open?') shown in console then You must check why modal is invisible. There can be many reasons, no height/width , to low z-index etc.

Converting Bootstrap 3 remote modal to Bootstrap 4 modal with parameters

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

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

How can I trigger a Bootstrap modal programmatically?

If I go here
http://getbootstrap.com/2.3.2/javascript.html#modals
And click 'Launch demo modal' it does the expected thing. I'm using the modal as part of my signup process and there is server side validation involved. If there are problems I want to redirect the user to the same modal with my validation messages displayed. At the moment I can't figure out how to get the modal to display other than a physical click from the user. How can I launch the model programmatically?
In order to manually show the modal pop up you have to do this
$('#myModal').modal('show');
You previously need to initialize it with show: false so it won't show until you manually do it.
$('#myModal').modal({ show: false})
Where myModal is the id of the modal container.
You should't write data-toggle="modal" in the element which triggered the modal (like a button), and you manually can show the modal with:
$('#myModal').modal('show');
and hide with:
$('#myModal').modal('hide');
This is a code for Bootstrap v5 without jQuery.
let myModal = new bootstrap.Modal(document.getElementById('myModal'), {});
myModal.show();
Demo
And this is a codesandbox demo to open modal on page load programmatically.
https://idu6i.csb.app/
Refs
https://getbootstrap.com/docs/5.0/components/modal/#via-javascript
https://getbootstrap.com/docs/5.0/components/modal/#show
If you are looking for a programmatical modal creation, you might love this:
http://nakupanda.github.io/bootstrap3-dialog/
Even though Bootstrap's modal provides a javascript way for modal creation, you still need to write modal's html markups first.
HTML
<!-- Button trigger modal -->
<button type="button" class="btn btn-primary btn-lg">
Launch demo 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">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel">Modal title</h4>
</div>
<div class="modal-body">
...
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
JS
$('button').click(function(){
$('#myModal').modal('show');
});
DEMO JSFIDDLE
you can show the model via jquery (javascript)
$('#yourModalID').modal({
show: true
})
Demo: here
or you can just remove the class "hide"
<div class="modal" id="yourModalID">
# modal content
</div>
​
I wanted to do this the angular (2/4) way, here is what I did:
<div [class.show]="visible" [class.in]="visible" class="modal fade" id="confirm-dialog-modal" role="dialog">
..
</div>`
Important things to note:
visible is a variable (boolean) in the component which governs modal's visibility.
show and in are bootstrap classes.
An example component & html
Component
#ViewChild('rsvpModal', { static: false }) rsvpModal: ElementRef;
..
#HostListener('document:keydown.escape', ['$event'])
onEscapeKey(event: KeyboardEvent) {
this.hideRsvpModal();
}
..
hideRsvpModal(event?: Event) {
if (!event || (event.target as Element).classList.contains('modal')) {
this.renderer.setStyle(this.rsvpModal.nativeElement, 'display', 'none');
this.renderer.removeClass(this.rsvpModal.nativeElement, 'show');
this.renderer.addClass(document.body, 'modal-open');
}
}
showRsvpModal() {
this.renderer.setStyle(this.rsvpModal.nativeElement, 'display', 'block');
this.renderer.addClass(this.rsvpModal.nativeElement, 'show');
this.renderer.removeClass(document.body, 'modal-open');
}
Html
<!--S:RSVP-->
<div class="modal fade" #rsvpModal role="dialog" aria-labelledby="niviteRsvpModalTitle" (click)="hideRsvpModal($event)">
<div class="modal-dialog modal-dialog-centered modal-dialog-scrollable" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="niviteRsvpModalTitle">
</h5>
<button type="button" class="close" (click)="hideRsvpModal()" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary bg-white text-dark"
(click)="hideRsvpModal()">Close</button>
</div>
</div>
</div>
</div>
<!--E:RSVP-->
The following code useful to open modal on openModal() function and close on closeModal() :
function openModal() {
$(document).ready(function(){
$("#myModal").modal();
});
}
function closeModal () {
$(document).ready(function(){
$("#myModal").modal('hide');
});
}
/* #myModal is the id of modal popup */
The same thing happened to me. I wanted to open the Bootstrap modal by clicking on the table rows and get more details about each row. I used a trick to do this, Which I call the virtual button! Compatible with the latest version of Bootstrap (v5.0.0-alpha2). It might be useful for others as well.
See this code snippet with preview:
https://gist.github.com/alireza-rezaee/c60da1429c36351ef4f071dec0ea9aba
Summary:
let exampleButton = document.createElement("button");
exampleButton.classList.add("d-none");
document.body.appendChild(exampleButton);
exampleButton.dataset.toggle = "modal";
exampleButton.dataset.target = "#exampleModal";
//AddEventListener to all rows
document.querySelectorAll('#exampleTable tr').forEach(row => {
row.addEventListener('click', e => {
//Set parameteres (clone row dataset)
exampleButton.dataset.whatever = e.target.closest('tr').dataset.whatever;
//Button click simulation
//Now we can use relatedTarget
exampleButton.click();
})
});
All this is to use the relatedTarget property. (See Bootstrap docs)
Here's how you do it with ternary operator
$('#myModal').modal( variable === 'someString' ? 'show' : 'hide');

Categories

Resources