How can I trigger a Bootstrap modal programmatically? - javascript

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

Related

Modify data in a modal window when loading it

I have a presentation with user notes. The button processing works for me, a modal window appears. Now I need to set its title and body when downloading. I get the body from the parent class of the button, no problem with that.
Here is my code:
const buttons = Array.from(document.querySelectorAll('.card .btn-info'));
function heangleClick() {
const parent = this.parentNode;
console.log($(this).parent().find('.fullBody').html());
$('#exampleModalCenter').modal('show');
$('#exampleModalLongTitle').val('123'); // not work
};
buttons.forEach((button) => {
button.addEventListener('click', heangleClick);
});
<div class="modal fade" id="exampleModalCenter" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLongTitle">Modal title</h5>
<button type="button" class="close" data-dismiss="modal" 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" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
<script src="~/js/showTittleTodo.js"></script>
How can i set values ​​in js file exampleModalLongTitle and modalBody
You try below which is not work.
$('#exampleModalLongTitle').val('123');// not work
Please replace below instead of that
$('#exampleModalLongTitle').text('123');
Try to set html or text instead val.
$('#exampleModalLongTitle').html('123');
try with this code:
$('#exampleModalCenter').modal('show');
$('#exampleModalCenter').on('shown.bs.modal', function() {
$('#exampleModalLongTitle').val('123');
})
Update your js as following, using shown.bs.modal event on modal element you can attach a callback which fires when the modal window is completely shown
const buttons = Array.from(document.querySelectorAll('.card .btn-info'));
function heangleClick() {
const parent = this.parentNode;
console.log($(this).parent().find('.fullBody').html());
$('#exampleModalCenter').one('shown.bs.modal', function() {
$('#exampleModalLongTitle').val('123');
})
$('#exampleModalCenter').modal('show');
};
buttons.forEach((button) => {
button.addEventListener('click', heangleClick);
});

Ionic javascript data-dismiss bootstrap modal not working

I'm trying to write a function in JavaScript that opens an model when a player enters a certain box. The model does pop up, but it no longer closes.
This is used to open the model :
The JavaScript:
superFight(){
function ModalLink(){
$('#myModal').modal('show');
}
ModalLink();
}
The HTML Model:
<div id="myModal" class="" 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">Modaldd Header</h4>
</div>
<div class="modal-body">
<p>Some text in the modal.</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
I already tried to use $('#myModal').modal('hide'); and $('#myModal').modal({ show: false});
This did not work. When I put it in the console, it gave :
> $('#myModal').modal({ show: false});
< false = $1
I also tried an onClick function in the close button to activate a function to close the modal, but this not work either.
Basically what I'm trying to do, is to open and close an modal programmatically. Whenever an superFight(); is started, it should pop up with some info. And the user should be able to close it when done.
I'm writing the code in an ionic app.
Figured it out.
I changed the code in superFight() to:
function superFight(){
$('#myModal').show();
$('#myModal').modal('show');
$( ".simplemodal-overlay" ).show();
}
Added an onClick the HTML:
<button type="button" class="close" data-dismiss="modal" onclick="CloseModalSpel()">×</button>
And then in the page, I added this function at the bottom:
function CloseModalSpel(){
$('#myModal').hide();
$( ".simplemodal-overlay" ).hide();
}
It now opens, and closes the modal.

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

Check if Bootstrap Modal currently Show

I'm trying to combine the Keypress plugin with Modal dialogs in Bootstrap. Based on this question, I can check if modal is open or closed using jquery.
However, I need to execute Keypress only if modal is closed. If it's open, I don't want to listen for keypresses.
Here's my code so far:
if(!$("#modal").is(':visible')) {
var listener = new window.keypress.Listener();
listener.simple_combo("enter", function() {
console.log('enter');
});
// I have over 20 other listeners
}
It's probably easier to leave the listeners attached and then conditionally exit them if the modal is open.
You could setup something like this:
var modalIsOpen = false
$('#myModal').on('shown.bs.modal', function(e) { modalIsOpen = true;})
$('#myModal').on('hidden.bs.modal', function(e) { modalIsOpen = false;})
Then just copy and paste the following line into all of your listeners.
if (modalIsOpen) return;
Demo in Stack Snippets
var modalIsOpen = false
$('#myModal').on('shown.bs.modal', function(e) { modalIsOpen = true;})
$('#myModal').on('hidden.bs.modal', function(e) { modalIsOpen = false;})
var listener = new window.keypress.Listener();
listener.simple_combo("s", function() {
if (modalIsOpen) return;
alert("You hit 's'");
});
<link href="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.2/css/bootstrap.css" rel="stylesheet"/>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.2/js/bootstrap.js"></script>
<script src="http://cdn.rawgit.com/dmauro/Keypress/master/keypress.js"></script>
<!-- Button trigger modal -->
<button type="button" class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal">
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">Don't Act On Key Presses</h4>
</div>
<div class="modal-body">
Try Hitting S
</div>
</div>
</div>
</div>
<p>Try Hitting S</p>
Bootstrap adds the in CSS class to a modal when it is open, thus (assuming your modal has id="modal":
var modalIsOpen = $('#modal.in').length > 0;

How to show a modal dialog using bootstrap

Earlier i was using a jquery dialog to show a pop-up message. However I need to use boostarp for my project and I am not able to figure out a way to actually show the pop-up.
The code that i used for my jquery dialog:
showUserWarningMessage: function (title, message, callback, scope, username) {
var $dialog = $("#dialog-move-user-warning");
$dialog.dialog({
resizable: false,
height: 450,
width: 580,
modal: true,
top: 200,
dialogClass: "warning-dialog",
title: title,
position: ["center", 200],
open: function () {
$dialog.find(".btn-default").on("click", function () {
$dialog.dialog("close");
});
$dialog.find(".btn-primary").on("click", function () {
$dialog.dialog("close");
if (callback) {
if (scope) {
callback.call(scope);
} else {
callback();
}
}
});
},
And he code im writing for bootstrap modal:
showAlertMessage: function(options) {
var $dialog = $("#dialog-move-user-warning");
$dialog.modal("show");
}
HTML:
<div class="modal fade" id="dialog-move-user-warning" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="myModalLabel">User Info</h4>
</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>
For some reason its not displaying anything on the screen, though the background gets disabled as though there is an overlay popped, but can see it. i tried changing the defaults set for the class="modal", but it didnt help.
What im i doing wrong, or anything additional needed for the overlay to display?
is there any css that i need to change?
Thanks in advance!
Below are multiple ways opening modal dialog using bootstrap
Method 1: Open modal window using javascript
$("#myModal").modal('show');
Method 2:
<button (click)="deleteStudent(item.student_id)" class='btn btn-danger'>Delete</button>
Method 3:
<button class='btn btn-success' data-toggle="modal" data-target="#myModalMore">Open</button>
Method 4:
<button href="#mypop" class="btn btn-success" data-backdrop="false" data-toggle="modal">Open Modal</button>
<div id="mypop" class="modal fade">
//modal code here
</div>
If you want to show a modal using Bootstrap, why don't you use Bootstrap?
1. Add the modal html to your page.
The modal html you've provided is valid, if you are not certain, you can find the exact code and more examples here: http://getbootstrap.com/javascript/#modals-examples
2. Add a trigger to your page.
Data-target should be equal to your modal ID, which is #dialog-move-user-warning in your case.
<button class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal">
Launch demo modal
</button>
3. Make sure you have bootstrap.js and bootstrap.css included on your website.
The Bootstrap modal relies heavily on bootstrap.js. You don't need everything, what you will find in the JSFiddle below is just enough.
http://jsfiddle.net/fgxmcnd2/3/

Categories

Resources