How do I call Bootstrap modal functions without jQuery? - javascript

In my app I am removing my jQuery dependencies.
I still use Bootstrap though. How can I call modal functions - $('#myModal').modal('show') and similar - without using jQuery?

If you are using Bootstrap (js), jQuery is required.
All you need to do is target the selector and toggle the CSS display. I did not include the Bootstrap (js) library, but I did keep the CSS.
Example taken from: https://getbootstrap.com/docs/4.0/components/modal/
const showModal = (selectorOrElement, show) => {
if (typeof selectorOrElement === 'string') {
selectorOrElement = document.querySelector(selectorOrElement)
}
selectorOrElement.style.display = show ? 'block' : 'none'
}
Array.from(document.querySelectorAll('.close')).forEach(closeButton => {
closeButton.addEventListener('click', (e) => {
let header = e.target.parentElement
let content = header.parentElement
let dialog = content.parentElement
let modal = dialog.parentElement
showModal(modal, false)
})
})
showModal('.modal', true)
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet"/>
<div class="modal" tabindex="-1" role="dialog">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">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">
<p>Modal body text goes here.</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary">Save changes</button>
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>

Bootstrap.js requires jQuery per the documentation.
Many of our components require the use of JavaScript to function. Specifically, they require jQuery, Popper.js, and our own JavaScript plugins.

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

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

Is there a way to get e.relatedTarget of bootstrap modal in document.ready ()?

I have two buttons that invoke the same modal, I have set data-button attribute to detect which button invoked the modal.
<button type="button" id="another" data-toggle="modal" data-target="#modal" class="btn btn-warning" data-button='another'>Add another</button>
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#modal" data-button="lab">Add lab</button>
what I wanted to do is to change a label inside a modal depending on the button invoker. I did so :
<script>
$('#modal').on('show.bs.modal', function(e) {
var $trigger = $(e.relatedTarget);
$('#vv_type').val($trigger.data('button'));
v_type = $trigger.data('button');
if (v_type == 'lab') {
$('#ModalLabel').html('changed label');
$("label[for='id_date_of_label']").html('label inside modal changed');
}
})
</script>
it works as expected only the first time when modal is shown , and after that the same changed label is always displayed whenever I click on the buttons, and this is logic due to $('#modal').on('show.bs.modal', function (e) {
Is there a way to declare v_type variable and send it to document.ready() function so that I make sure that the script will run every time I click on buttons invoking the modal (not only the first time?)
Your original code still works for me. The only part missing is the else condition for if (v_type == 'lab') {. I can see the label change on each button click.
$('#myModal').on('show.bs.modal', function (e) {
var $trigger = $(e.relatedTarget);
//$('#vv_type').val($trigger.data('button'));
v_type = $trigger.data('button');
if (v_type == 'lab') {
$('#buttonText').html(v_type);
//$("label[for='id_date_of_label']").html('label inside modal changed');
}
else
{
$('#buttonText').html(v_type);
//$("label[for='id_date_of_label']").html('label inside modal changed');
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<button type="button" data-button="lab" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal">Open Modal</button>
<button type="button" data-button="lab 123" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal">Open Modal</button>
<div id="myModal" 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">×</button>
<h4 class="modal-title">Modal Header</h4>
</div>
<div class="modal-body">
<p id="buttonText"></p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
I have solved this by getting the data-button from a hidden input vv_type on the modal (my modal has already a form in it ) and I added this script which is ran each time a modal is shown:
<script>
$(document).ready(function () {
$('.modal').on('show.bs.modal', function (e) {
if ($('#vv_type').val() == 'lab') {
$('#ModalLabel').html('changed label');
$("label[for='id_date_of_label']").html('label inside modal changed');
}
else {
$('#ModalLabel').html('origin label');
$("label[for='id_date_of_label']").html('label inside modal origin');
}
});
});
</script>

Set focus on a input control contained in a second level bootstrap modal

I'm using Vue.js 2.1.10 and Bootstrap 3.3.7 to show a modal that opens another modal dialog. Each modal dialog is contained in a distinct component. Inside the 1st component, there is a reference to the 2nd component (select-travler).
According to the Bootsrap documentation, I have to set the focus by listening to the event shown.bs.modal. This works great to set the focus on an input control contained in the 1st modal. Problem: this way doesn't work when the modal is above another modal.
The 1st modal component looks like this:
<template>
<div ref="tripEdit" class="modal fade" role="dialog">
<!-- Inbeded component -->
<select-travler ref="selectTravler"></select-travler>
<!-- /Inbeded component -->
<div class="modal-lg modal-dialog">
<div class="modal-content">
<div class="modal-body container form-horizontal">
<div class="form-group">
<label for="travler_name" class="control-label">
Travler's name
</label>
<input id="travler_name" ref="travler_name"
v-model="travler_name"/>
</div>
</div>
</div>
</div>
</div>
</template>
<script>
export default {
data () {
return {
travler_name: null,
}
},
methods: {
show (operationType) {
$(this.$refs.tripEdit).modal('show');
let that = this;
$(this.$refs.tripEdit).on('shown.bs.modal', function () {
$(that.$refs.travler_name).focus();
});
if (operationType === 'newTravel') {
this.$refs.selectTravler.show();
}
},
},
}
</script>
The 2nd component contains a similar layout with the following show method:
show () {
$(this.$refs.selectTravler).modal('show');
let that = this;
$(this.$refs.selectTravler).on('shown.bs.modal', function () {
$(that.$refs.people_names).focus();
});
},
When the 2nd modal opens, the focus is still on the 1st modal behind the 2nd modal dialog (I can see the caret blinking in travler_name). How can I set the focus on people_names when the 2nd modal is shown?
I think there are really several issues at play here. First, as I mentioned in the comment above, you are not properly adding and removing the shown.bs.modal event handlers.
Second, because your second modal is nested inside the first modal, the shown.bs.modal event will bubble up to the parent modal and it's handler will fire. Initially I thought stopPropagation would be a good way to handle this, but in the end, I simply de-nested the submodal component in the template.
Here is an example of this behavior actually working.
console.clear()
Vue.component("sub-modal", {
template: "#submodal",
methods: {
show() {
$(this.$el).modal("show")
},
onShown(event) {
console.log("submodal onshown")
this.$refs.input.focus()
}
},
mounted() {
$(this.$el).on("shown.bs.modal", this.onShown)
},
beforeDestroy() {
$(this.$el).off("shown.bs.modal", this.onShown)
}
})
Vue.component("modal", {
template: "#modal",
methods: {
show() {
$(this.$refs.modal).modal("show")
},
showSubModal() {
this.$refs.submodal.show()
},
onShown(event) {
console.log("parent")
this.$refs.input.focus()
}
},
mounted() {
$(this.$refs.modal).on("shown.bs.modal", this.onShown)
},
beforeDestroy() {
$(this.$refs.modal).off("shown.bs.modal", this.onShown)
}
})
new Vue({
el: "#app",
})
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://unpkg.com/vue#2.2.6/dist/vue.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>
<div id="app">
<modal ref="modal"></modal>
<button #click="$refs.modal.show()" class="btn">Show Modal</button>
</div>
<template id="submodal">
<div class="modal fade" tabindex="-1" role="dialog">
<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">Modal title</h4>
</div>
<div class="modal-body">
<input ref="input" type="text" class="form-control">
</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><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
</template>
<template id="modal">
<div>
<div ref="modal" class="modal fade" tabindex="-1" role="dialog">
<div class="modal-dialog modal-lg" 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">Modal title</h4>
</div>
<div class="modal-body">
Stuff
<input ref="input" type="text" class="form-control">
</div>
<div class="modal-footer">
<button #click="showSubModal" type="button" class="btn btn-primary">Show Sub Modal</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
<sub-modal ref="submodal"></sub-modal>
</div>
</template>
Also, for future readers, I got some useful information about how to construct the template for the modal component used above from this answer. Specifically, unless you manually specify a z-index for the modal, the modal that appears last in HTML will have a higher z-index. The implication being the submodal component needs to come second in the template.
I ran into a similar issue. A b-modal forces focus to stay in the modal. You can disable it by adding a no-enforce-focus attribute.
no-enforce-focus Boolean false Disables the enforce focus routine
which maintains focus inside the modal
https://bootstrap-vue.org/docs/components/modal
This means that the element you're trying to focus is not properly referenced.
Trying to console.log(element); the line before focussing people_names. To see if you're getting the right element.
show () {
$(this.$refs.selectTravler).modal('show');
let element = this.$refs.people_names;
$(this.$refs.selectTravler).on('shown.bs.modal', function () {
$(element).focus();
});
},
Have you considered v-show to open and close your modals ?

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