Bootstrap v5 modal show issue - javascript

I decided to go ahead and update my site to the latest version of Bootstrap, version 5.0 and am having difficulty getting modals to work. Reading the migration guide said nothing about breaking modals and my site worked perfectly before. My code uses javascript/jQuery to fire off the modal after the ajax loads the text. The ajax part still works fine, but it's not firing the modal after it retrieves it. I'm using the latest bootstrap.bundle.min.js.
$( document ).ready(function() {
$('.hourModal').click(function(){
var obj_id = $(this).data('id');
$.ajax({
url: 'ajax-multi.php',
type: 'POST',
data: {obj_id: obj_id,role:'some_role'},
//dataType: 'html',
success: function(response){
$('.modal-body').html(response);
//$('#hourModal').modal('show'); //Old way that worked great
var hourModal = new bootstrap.Modal(document.getElementById('hourModal'));
hourModal.show(); // New way I tried from the Bootstrap documentation
}
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.0.0/dist/js/bootstrap.bundle.min.js" integrity="sha384-p34f1UUtsS3wqzfto5wAAmdvj+osOnFyQFpp4Ua3gs/ZVWx6oOypYoCJhGGScy+8" crossorigin="anonymous"></script>
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.0/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-wEmeIV1mKuiNpC+IOBjI7aAzPcEZeedi5yW5f2yOq55WWLwNGmvvx4Um1vskeMj0" crossorigin="anonymous">
<!-- Button -->
<button type="button" class="btn btn-secondary btn-sm py-0 me-1 hourModal" data-id="1">Blocks</button>
<!-- Modal -->
<div class="modal fade" id="hourModal" tabindex="-1">
<div class="modal-dialog modal-xl">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Object Times</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"> </button>
</div>
<div class="modal-body">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
The error I get is: Uncaught TypeError: BACKDROP: Option "rootElement" provided type "null" but expected type "element".
Any help is greatly appreciated!
UPDATE:
As described below, I had to move bootstrap.min.js to the end of the page, after </body> and leave where I call jquery.min.js at the top in the header. Anyone have any idea why it has to be done this way?

Move your <script> with bootstrap at the end of the <body>. It fixed my Bootstrap 5 modal issue.

This issue is fixed in currently available 5.0.1

UPDATE:
Fixed in Bootstrap 5.0.1
I had the same problem. The only difference I use Webpack to build.
If you want to load your scripts from head section you can try to add async option.
This fixed the issue for me.
<script src="..." async="async"></script>

I had the same problem. I called jquery.js and bootstrap.js at the end of the html and before /body and it worked correctly.

mamantoha's suggestion seems to be the better way to handle this since it doesn't require moving the outside the section, and some people may have dependencies that require bootstrap to be loaded ahead of other scripts in the section.

In bootstrap 4 or 5 you maybe forgetting the '#' in
data-bs-target="#exampleModal"

Related

Can't get Bootstrap toast to close or autohide to work

I am trying to implement Bootstrap 5 toasts in my ASP.NET web application, using the following code...
HTML
<div class="row">
<div class="toast" id="companyUpdOK" name="companyUpdOK" role="alert" data-delay="5000" data-autohide="true" aria-live="assertive" aria-atomic="true">
<div class="toast-header">
<strong class="me-auto">Bootstrap</strong>
<small>11 mins ago</small>
<button type="button" class="btn-close" data-bs-dismiss="toast" aria-label="Close"></button>
</div>
<div class="toast-body">
Hello, world! This is a toast message.
</div>
</div>
</div>
JavaScript
$('#companyUpdOK').toast(); // code to set up toast
...
$('#companyUpdOK').show(); // and later, the code to display the toast
So, the toast shows up, but the autohide doesn't work, and the close button doesn't work either. I have tried every combination I could find, including setting the options when initializing the toast, as in:
$('#companyUpdOK').toast({delay: 5000, autohide: true});
None of these work. What am I doing wrong?
Your code works with some changes
Bootstrap 5 doesn't require jQuery and the native JavaScript library is very easy to use. Yet, if you do use jQuery then keep in mind that the documentation may not show you the right way to do something using jQuery.
Here are a few issues to watch for:
1. Initialization
When Bootstrap 5 detects jQuery it loads jQuery plug-ins on the DOMContentLoaded event. Importantly, this appears to happen AFTER the jQuery ready event. If you need to do something with Bootstrap when the page loads then add a handler like:
document.addEventListener("DOMContentReady", function() {
$("#mytoast").toast();
});
2. jQuery plug-ins
The plug-ins that Bootstrap adds to jQuery are just wrappers for Bootstrap native JavaScript methods. The syntax is different and looking at the documentation can mislead you about how to do it with jQuery.
For example, the native JavaScript way of showing a Toast:
let toast = bootstrap.Toast.getOrCreateInstance(myToastEl);
toast.show();
Yet, if you are using jQuery this will not work, even though it might seem so from the documentation.
let toast = $(myToastEl).toast();
toast.show();
With jQuery you instead need to do this:
$(myToastEl).toast("show");
3. Data Attributes
Be aware that attributes have a new prefix: data-bs-<name> So if you use data-delay rather than the correct data-bs-delay then it will not work correctly.
Demo Snippet
The snippet incorporates these changes into the original code and the Bootstrap toast displays as expected.
test.onclick = function() {
$('#companyUpdOK').toast("show");
}
document.addEventListener("DOMContentLoaded", function() {
$('#companyUpdOK').toast();
});
<button id="test" class="btn btn-primary m-1">Show Toast</button>
<div aria-live="polite" aria-atomic="true" class="bg-dark position-relative bd-example-toasts">
<div class="toast-container position-absolute p-3" id="toastPlacement">
<div class="toast" id="companyUpdOK" name="companyUpdOK" role="alert" data-bs-delay="2000" data-bs-autohide="true" aria-live="assertive" aria-atomic="true">
<div class="toast-header">
<strong class="me-auto">Bootstrap</strong>
<small>11 mins ago</small>
<button type="button" class="btn-close" data-bs-dismiss="toast" aria-label="Close"></button>
</div>
<div class="toast-body">
Hello, world! This is a toast message.
</div>
</div>
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.2/dist/css/bootstrap.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.0.2/dist/js/bootstrap.bundle.js"></script>
if you are using bootstrap 5 then you should use data-bs-autohide="true" and data-bs-delay="10000" you missed bs

VueJS activate boostrap modal from Javascript without the use of jQuery

I am working on an application using vuejs. When a user logins to my application, i would like to show an error (if any) using bootstrap modal instead of the old fashion alert. Is there a way to "pop" the modal from javascript without the use of jQuery?
Thank you :)
$("#loginerror").modal();
The code above uses jQuery but I do not want to use that.
I have tried using the ref method but it shows an error saying
this.$refs.loginerror.modal is not a function
Below is my code for the ref method:
<!-- Modal -->
<div ref="loginerror" 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">Login Error</h4>
</div>
<div class="modal-body">
<p id = "loginerrormsg"></p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
snippets of Javascript code
.catch((error) => {
document.getElementById("loginerrormsg").innerHTML = error;
this.$refs.loginerror.modal();
});
Since you are using Vuejs you should use refs, on your modal in the template set your reference for example:
<div ref="myModal">
</div>
and in your code you can activate it as follows:
this.$refs.myModal.modal();
This is the best way to access the DOM in vue
according to bootstrap source code, this is how to hide modal.
_hideModal() {
this._element.style.display = 'none'
this._element.setAttribute('aria-hidden', true)
this._element.removeAttribute('aria-modal')
this._element.removeAttribute('role')
this._isTransitioning = false
this._showBackdrop(() => {
$(document.body).removeClass(CLASS_NAME_OPEN)
this._resetAdjustments()
this._resetScrollbar()
$(this._element).trigger(EVENT_HIDDEN)
})
}
it will change style display, aria-hidden, class name, and other stuff.
here is a simple reimplementation. may not work properly. but it does show and hide modal.
const toggleModal = (modal) => {
if (modal.classList.contains("show")) {
modal.classList.remove("show");
modal.style.display = "none";
modal.setAttribute("aria-hidden", "true");
} else {
modal.classList.add("show");
modal.style.display = "block";
modal.setAttribute("aria-hidden", "false");
}
}
Bootstrap 4:
Many of our components require the use of JavaScript to function. Specifically, they require jQuery, Popper.js, and our own JavaScript plugins.
So Bootstrap 4 required jQuery as dependency. If you still don't want to use jQuery in your application, you can migrate to Bootstrap 5.
Bootstrap 5 dropped jQuery dependency and is not required any more.
For more details on Bootstrap 5 you can visit: https://getbootstrap.com/docs/5.0/getting-started/javascript/
For more details on Bootstrap 4 you can visit:
https://getbootstrap.com/docs/4.1/getting-started/introduction/

Bootstrap $('#myModal').modal('show') is not working

I'm not sure why but all the modal functions are not working with me.
I checked the version and the load they are fine.
I keep getting this error message:
Uncaught TypeError: $(...).modal is not a function
for the hide I already found an alternative.
instead of:
$('#myModal').modal('hide');
I used this :
$('#myModal .close').click();
And it works perfectly.
The problem now is with the show
$('#myModal').modal("show");
I also tried both
$('#myModal').modal("toggle");
And:
$('#myModal').modal();
but unfortunately none of them is working.
Here html code -when the button is clicked I will do some verification and handle a json data from the web service if it succeed then I want show my modal- everything is working except the show.
<button type="button" id="creatNewAcount" class="btn btn-default" data-toggle="modal">Sign up</button>
if there's any alternative I would like to know it.
Most common reason for such problems are
1.If you have defined the jquery library more than once.
<script type="text/javascript" src="//code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<div class="modal fade" id="myModal" aria-hidden="true">
...
...
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
The bootstrap library gets applied to the first jquery library but when you reload the jquery library, the original bootstrap load is lost(Modal function is in bootstrap).
2.Please wrap your JavaScript code inside
$(document).ready(function(){});
3.Please check if the id of the modal is same
as the one you have defined for the component(Also check for duplication's of same id ).
<div class="modal fade" id="myModal" aria-hidden="true">
...
...
</div>
Note: Remove fade class from the div and enjoy it should be worked
This can happen for a few reasons:
You forgot to include Jquery library in the document
You included the Jquery library more than once in the document
You forgot to include bootstrap.js library in the document
The versions of your Javascript and Bootstrap does not match. Refer bootstrap documentation to make sure the versions are matching
The modal <div> is missing the modal class
The id of the modal <div> is incorrect. (eg: you wrongly prepended # in the id of the <div>)
# sign is missing in the Jquery selector
I got same issue while working with Modal Popup Bootstrap , I used Id and trigger click event for showing and hidding modal popup instead of $("#Id").modal('show') and $("#id").modal('hide'),
`
<button type="button" id="btnPurchaseClose" class="close" data dismiss="modal" aria-label="Close"> <span aria-hidden="true">×</span></button>
<a class="btn btn-default" id="btnOpenPurchasePopup" data-toggle="modal" data target="#newPurchasePopup">Select</a>
$('#btnPurchaseClose').trigger('click');// for close popup
$('#btnOpenPurchase').trigger('click');`// for open popup
My root cause was that I forgot to add the # before the id name. Lame but true.
From
$('scheduleModal').modal('show');
To
$('#scheduleModal').modal('show');
For your reference, the code sequence that works for me is
<script>
function scheduleRequest() {
$('#scheduleModal').modal('show');
}
</script>
<script src="<c:url value="/resources/bootstrap/js/bootstrap.min.js"/>">
</script>
<script
src="<c:url value="/resources/plugins/fastclick/fastclick.min.js"/>">
</script>
<script
src="<c:url value="/resources/plugins/slimScroll/jquery.slimscroll.min.js"/>">
</script>
<script
src="<c:url value="/resources/plugins/datatables/jquery.dataTables.min.js"/>">
</script>
<script
src="<c:url value="/resources/plugins/datatables/dataTables.bootstrap.min.js"/>">
</script>
<script src="<c:url value="/resources/dist/js/demo.js"/>">
</script>
Use .modal({show:true}) and .modal({show:false}) instead of ('show') and ('hide') ... it seems to be bootstrap / jquery version combination dependent. Hope it helps.
the solution of 'bootstrap modal is not opening' is, put your Jquery CDN first in the head tag (after starting head tag).
I wasted two days in finding this problem.
Please,
try and check if the triggering button has attribute type="button".
Working example:
<button type="button" id="trigger" style="visibility:visible;" onclick="modal_btn_click()">Trigger Modal Click</button>
<!-- Modal -->
<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog modal-sm">
<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>This is a small modal.</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<script >
function modal_btn_click() {
$('#myModal').modal({ show: true });
}
</script>
Try This without paramater
$('#myModal').modal();
it should be worked
are you sure that the id of the modal is "myModal"? if not then the call will not trigger it.
also - just from reading your post - you are triggering a function / validation with this button
<button type="button" id="creatNewAcount" class="btn btn-default" data-toggle="modal">Sign up</button>
and then if all is well - you want to trigger the modal. - if this is hte case - then you should remove the toggle from this button click. I presume you have an event handler tied to this click? you need the .modal("show") as a part of that function. not toggled from this button. also - is this id correct "creatNewAcount" as opposed to this spelling "createNewAccount"
<button type="button" id="creatNewAcount" class="btn btn-default" >Sign up</button>
use the object to call...
<a href="#" onclick='$("#myModal").modal("show");'>Try This</a>
or if you using ajax to show that modal after get result, this is work for me...
$.ajax({ url: "YourUrl",
type: "POST", data: "x=1&y=2&z=3",
cache: false, success: function(result){
// Your Function here
$("#myModal").modal("show");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script><script type="text/javascript" src="//code.jquery.com/jquery-1.11.3.min.js"></script>
the first googleapis script is not working now a days use this second scripe given by jquery
jQuery lib has to be loaded first. In my case, i was loading bootstrap lib first, also tried tag with target and firing a click trigger. But the main issue was - jquery has to be loaded first.
Please also make sure that the modal div is nested inside your <body> element.
After trying everything on the web for my issue, I needed to add in a small delay to the script before trying to load the box.
Even though I had put the line to load the box on the last possible line in the entire script. I just put a 500ms delay on it using
setTimeout(() => { $('#modalID').modal('show'); }, 500);
Hope that helps someone in the future. 100% agree it's prob because I don't understand the flow of my scripts and load order. But this is the way I got around it
In my case, bootstrap.css and bootstrap.js versions are mismatched.
It is working if I remove the fade class. But the background is disappeared.
I added the same version of bootstrap files. Now it is working perfectly.
Thank you #Mohammed Shareef C.
Another use case that may be the cuplrit
My problem was that I had a jquery selector that was using a variable that was not assigned immediately.
My modal had a dynamic ID
<div class="modal fade" id="{{scope.modalId}}"... >
This is in angularJS, so the valud of scope.modalID wasn't being bound until $scope.onInit
vm.$onInit = function () {
$( `#${vm.modalId}` ).on('shown.bs.modal', function(){
console.log('WORKS')
});
zzz
Make sure your script tag is closed with another script tag like below
before
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"/>
After
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

time-picker in bootstrap modal dialog

I am trying to implement a time-picker in a boostrap modal dialog. However when I open the dialog the time-picker still looks like a normal text field which makes me believe that this jquery code is not running:
$('#timepicker1').timepicker(); // shown below
However I am able to get the time-picker to display using very similar code on a normal webpage. The problem seems specific to displaying it in a modal dialog.
Here is a link to the time-picker that I am using:
http://jdewit.github.io/bootstrap-timepicker/
Here is my modal dialog:
<div class="modal fade" id="dialog" tabindex="-1" role="dialog" aria-labelledby="basicModal" 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">close</button>
<h4 class="modal-title" id="myModalLabel">New Event</h4>
</div>
<div class="modal-body">
<div class="input-append bootstrap-timepicker">
<input id="timepicker1" type="text" class="input-small">
<span class="add-on"><i class="icon-time"></i></span>
</div>
</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>
Here is my script that is suppose to initialize the time-picker
$( document ).ready(function() {
//$('#table').editableTableWidget();
$( "#btn-new-event" ).click(function() {
$('#dialog').modal('show');
$('#timepicker1').timepicker(); // not running properly
});
});
Any help would be greatly appreciated!
For me, I had to do this to make it work:
.bootstrap-timepicker-widget.dropdown-menu {
z-index: 99999!important;
}
and of course, remove:
template: 'modal'
ibrahimyilmaz gave you the right answer, exactly as shown on the bootstrap timepicker official site.
The only thing that maybe serves as a more precise indication here is that timepicker only works with bootstrap v2.x.
If you want to use bootstrap 3.x, you have to read the migration doc and perform the required changes. If you need help on that, just give me a sign :) Or use timepicker bootstrap3 wich is a fork of the one you have used.
Check this link example to see a working example. Check on the +view Source link to see all the required scripts and links.
Hope it's useful!
$('#timepicker1').timepicker({
template: 'modal'
});
It's a reported bug https://github.com/jdewit/bootstrap-timepicker/issues/326
you have to change the z-order as mentioned by #eugene1832:
.bootstrap-timepicker-widget.dropdown-menu {
z-index: 1050!important;
}
AND you also need to remove the initialization option:
template: 'modal'
To update the answers to this question: bootstrap-timepicker now supports Bootstrap 3, but this issue with modals is a known bug.
The bug is still open at this time, but one user suggested adding this piece of code to your css file to make the timepicker visible:
.bootstrap-timepicker-widget.dropdown-menu {
z-index: 1050!important;
}
I would note that this solution did not work for me, but it is currently listed as a possible solution. I'll try to update this response when the issue is either resolved on Github or when someone suggests another method.
Add this code for line #666 in bootstrap-timepicker.js file. It's work for me
var index_highest = 0;
$(".modal").each(function() {
// always use a radix when using parseInt
var index_current = parseInt($(this).css("zIndex"), 10);
if (index_current > index_highest) {
index_highest = index_current;
}
});
var zIndex = parseInt(this.$element.parents().filter(function() { return $(this).css('z-index') !== 'auto'; }).first().css('z-index'), 10) + index_highest;

Modal error - Uncaught TypeError: undefined is not a function modal

Im using the following code and I got error in delete in the JS($("#deleteModal").modal("show");),any idea what can be wrong here ?
Im using MVC5 project
the error is
Uncaught TypeError: undefined is not a function
<!-- Modal -->
<div class="modal fade" id="deleteModal" tabindex="-1" role="dialog" aria-labelledby="deleteModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button>
<h4 class="modal-title" id="deleteModalLabel">Delete Item</h4>
</div>
<div id="deleteModalBody" class="modal-body"></div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<script>
$(function () {
$("#deleteModal").modal("hide"); // initially hides the modal pop-up until needed
$(".deleteLink").on("click", function () {
$.get('#Url.Action("GetDeletePartial")', { id: $(this).prop("id") }, function (data) {
$("#deleteModalBody").html(data);
$("#deleteModal").modal("show"); // shows the modal pop-up now that we have our partial view
});
});
});
</script>
when I try it like following it fail in the begging of the script with the same error
#section scripts
{
<script src="~/Scripts/jquery-2.1.1.min.js"></script>
<script>
$(function () {
$("#deleteModal").modal("hide"); // initially hides the modal pop-up until needed
$(".deleteLink").on("click", function () {
$.get('#Url.Action("GetDeletePartial")', { id: $(this).prop("id") }, function (data) {
$("#deleteModalBody").html(data);
$("#deleteModal").modal("show"); // shows the modal pop-up now that we have our partial view
});
});
});
</script>
}
It seems that you are attempting to make a model dialog using some third-party jQuery plugin, but you foget to make a reference to that plugin's javascript file.
To confirm this, i wonder which line does the exception occurs on? Is it on the line of first line of your ready callback?
$("#deleteModal").modal("hide");
If so, please check your script reference. Just add a <script> tag with a src to that file before your script block.
Update:
As you comments, the exception does not occurs on that line. So you may use a debugger(such as Chrome developer tools) to find out which function-call fails. You can set the debugger to pause the excution on exceptions.
In chrome developer tools, you can switch to Source tab and click the last icon on right-top of the side-bar on the right to enable this feature. Here's an awesome answer with snapshots: https://stackoverflow.com/a/17324511/1817042
Had the same error on standalone plain old HTML+Javascript page.
Apparently caused by socket.io.js which script tag was initially placed after jquery and bootstrap.js script tags.
Moving socket.io.js script tag before jquery and bootstrap resolved the issue for me.

Categories

Resources