uncaught ReferenceError: tgl is not defined - javascript

I dont really know what is causing the error since I'm new to JavaScript. I've referenced the variable in the header with js:
document.addEventListener('DOMContentLoaded', function() {
var calendarEl = document.getElementById('calendar');
var calendar = new FullCalendar.Calendar(calendarEl, {
selectable: true,
selectHelper: true,
select: function date(start, end, alldays){
$("#BookingModal").modal('toggle');
var tgl=moment(start).format('DD-MM-YYYY')
}
});
calendar.render();
});
And when I want to use the variable in the body of the html, it throws the error:
uncaught ReferenceError: tgl is not defined
<h1 class="modal-title fs-5" id="exampleModalLabel"> <script type="text/javascript">document.write(tgl)</script></h1>

The modal title you whish to have is dynamic based on the calendar cell that was clicked.
So you have to wait for the user to click on a calendar cell to know what is the startDate provided in this select callback.
The code below will be exectuted on page load while parsing the HTML...
Long before the rest of your code that will execute after DOMContentLoaded has fired.
<script type="text/javascript">document.write(tgl)</script>
The events are firing in this order and that is how tgl should be used in each of them:
DOMContentLoaded -- tgl is declared
FullCalendar's select -- tgl value is setted
show.bs.modal -- tgl value is used
document.addEventListener("DOMContentLoaded", function () {
// Have the tgl variable at global scope
let tgl;
// On modal open, set the modal title
$("#BookingModal").on("show.bs.modal", function (event) {
$("#BookingModal").find(".modal-title").text(tgl);
});
// FulCalendar
var calendarEl = document.getElementById("calendar");
var calendar = new FullCalendar.Calendar(calendarEl, {
selectable: true,
select: function date(start, end, alldays) {
// Set tgl here
tgl = moment(start.startStr).format("DD-MM-YYYY");
// Open modal
$("#BookingModal").modal("show");
}
});
calendar.render();
});
<link href="https://cdn.jsdelivr.net/npm/bootstrap#4.0.0/dist/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js#1.12.9/dist/umd/popper.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#4.0.0/dist/js/bootstrap.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/fullcalendar#6.0.2/index.global.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.4/moment.min.js"></script>
<div id="calendar"></div>
<div class="modal fade" id="BookingModal" 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">This title will be replaced</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
Some modal body here...
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary" data-dismiss="modal">Ok</button>
</div>
</div>
</div>
</div>
CodePen
Also, notice I used start.startStr to pass to moment.js. You can console log that start object of FullCalendar to understand why.

Related

select box value not setting on bootstrap modal

Problem:
A value of select box is not setting in modal,
But when reloading a page and open a modal it sets select box value.
Expected:
In both cases, select box values are loading correctly but the value is not set.
jQuery:
function showModal() {
var selectbox_options = '<option value=""></option><option value="0"></option><option value="1"></option>';
//Above selectbox options are dynamically created using jquery each.
var selected_value = "0";
$('#modal').modal({
show: true,
backdrop: 'static',
keyboard: false
});
//I tried both by placing these below two lines above and inside show.bs.modal callbacks
$('#modal').on('shown.bs.modal', function(e) {
$('#modal').find(".dropdown-box").find('option').not(':first').remove();
$('#modal').find('.dropdown-box').append(selectbox_options).val(selected_value).trigger('change');
});
}
HTML:
<button type="button" onclick="showModal();"></button>
Check this,
You assigned the value as selected_value but used as selectbox_value
Also, I have given the option values too, in order to recognize the change in select box
function showModal() {
var selectbox_options = '<option value=""></option><option value="0">0</option><option value="1">1</option>';
//Above selectbox options are dynamically created using jquery each.
var selected_value = "0";
$('#modal').modal({
show: true,
backdrop: 'static',
keyboard: false
});
//I tried both by placing these below two lines above and inside show.bs.modal callbacks
$('#modal').on('shown.bs.modal', function(e) {
$('#modal').find(".dropdown-box").find('option').not(':first').remove();
$('#modal').find('.dropdown-box').append(selectbox_options).val(selected_value).trigger('change');
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="
https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" />
<button type="button" onclick="showModal();">open</button>
<div class="modal fade" id="modal">
<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">
<select class="dropdown-box"></select>
</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>

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;

Function to append modal

I have 3 modals that all have the same format and are activated by different onclicks (Create Contact, Update Contact, Delete Contact). I am wanting the modal-title and modal-body to change depending on which button was clicked. How would I go about creating a function that appends the modal content depending on which button was clicked? Thank you for your help!
<div id="myModal" class="modal fade">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title">Confirmation</h4>
</div>
<div class="modal-body">
<p>Contact Created!</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">OK</button>
</div>
</div>
</div>
I have written the JavaScript "BootstrapModel" class for the same purpose.
It also depends on jQuery so don't forget to embed jQuery before using this class.
class is :
var BootstrapModal = (function (options) {
var defaults = {
modalId: "#confirmModal",
btnClose: "#btnClose",
title: "Confirm",
content: "Some bootstrap content",
onClose: function () {
},
onSave: function () {
}
};
defaults = options || defaults;
var $modalObj = $(defaults.modalId);
var hideModal = function () {
$modalObj.modal("hide");
};
var showModal = function () {
$modalObj.modal("show");
};
var updateModalTitle = function (title) {
defaults.title = title;
//$($modalObj).find(".modal-title").eq(0).html(title);
$modalObj.find(".modal-title").eq(0).html(title);
};
var updateModalBody = function (content) {
defaults.content = content;
$modalObj.find(".modal-body").eq(0).html(content);
};
return {
getDefaults: function () {
return defaults;
},
hide: function () {
hideModal();
},
show: function () {
showModal();
},
updateTitle: function (title) {
updateModalTitle(title);
return this;
},
updateBody: function (body) {
updateModalBody(body);
return this;
}
}
});
Usage :
var emailModal = new BootstrapModal({modalId: "#confirmModal"});
emailModal.updateTitle("Mail sent successfully").updateBody("<br/>This box will automatically close after 3 seconds.").show();
// Hide the Modal
emailModal.hide();
HTML Structure for the Modal:
<div class="modal fade" id="confirmModal" role="dialog" aria-labelledby="thankyouModal" aria-hidden="true" style="overflow-y: hidden;">
<div class="modal-dialog" style="padding-top: 225px">
<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="thankyouModal">Thank you</h4>
</div>
<div class="modal-body">
Thank you. We'll let you know once we are up.
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
The way I got around this is by loading the data in from external files. So you'd have your initial declaration of your modal box (just the surrounding div), and then in each file you have the containing code for the rest of the modal, then use a bit of jQuery to fire them off:
HTML (in main file)
<div class="modal" id="modal-results" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
</div>
JQuery
$('#create-contact').click(function(){
e.preventDefault();
$("#modal-results").html('create-contact.html');
$("#modal-results").modal('show');
});

fullcalendar bootstrap modal with external event data

I'm using full calendar with a asp.net MVC 5 application.
When I click a on a empty space I get a modal view for creating a event. This works perfect.
When I click on a event I want to get the event data but also some other data then just the start date end date and description.
I have the following:
eventRender: function (event, element) {
var id = event.id;
element.popover({
placement: 'top',
html: true,
content: '<button id="customers" class="btn btn-default" onclick="KlantenModal(' + id + ')">Klant overzicht</button>',
animation: true
});
}
The function that calls the modal.
function KlantenModal(event) {
$('#klanten #eventId').val(event);
$('#klanten').modal('show');
}
and the bootstrap modal:
<div class="modal fade" id="klanten" 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-hidden="true">×</button>
<h4 class="modal-title" id="myModalLabel">Klanten</h4>
</div>
<div class="modal-body">
/* here I want some Data eg. names of customers */
<input type="hidden" id="eventId" name="eventId" />
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
<button type="submit" class="btn btn-primary"></button>
</div>
</div>
</div>
If i understood you well the only thing you have to do is to add fields to the event like this:
Somewhere in your code populate an array with diferent customers and add that array to the event properties
var customers = [];
customers.push("im customer x");
customers.push("im customer y");
...
events:[
{
'start': 2013-12-30,
'end': 2013-12-30,
'allDay': true,
'customers': customers
}
and when you click on the event and access the event fields you will get the customers field wich contains your customers for that day.

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