Fullcalender V5 RefetchEvents issue - javascript

I am using Fullcalender Scheduler V5.
I added calendar.refetchEvents(); at the end of eventDrop, eventResize, eventClick also. It is working well. But when I use it in other functions to add /edit the events, it is not working.Here is my code:
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8' />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
<script src='moment-timezone.js'></script>
<script src='lib/locales-all.js'></script>
<link href='fullcalender_scheduler/main.css' rel='stylesheet' />
<script src='fullcalender_scheduler/main.js'></script>
<script src='fullcalender_scheduler/ja.js'></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
<script>
document.addEventListener('DOMContentLoaded', function() {
var calendarEl = document.getElementById('calendar');
var calendar = new FullCalendar.Calendar(calendarEl, {
schedulerLicenseKey: 'GPL-My-Project-Is-Open-Source',
eventTimeFormat: { hour: 'numeric', minute: '2-digit' },
businessHours: true,
height: '100%',
aspectRatio: 1.8,
editable: true, // enable draggable events
now: new Date(),
scrollTime: '00:00', // undo default 6am scrollTime
headerToolbar: {
left: 'today prev,next',
center: 'title',
right: 'resourceTimelineDay,resourceTimelineTenDays,timeGridWeek,dayGridMonth,listWeek'
},
initialView: 'resourceTimelineDay',
views: {
resourceTimelineTenDays: {
type: 'resourceTimeline',
duration: { days: 10 },
buttonText: '10 days'
}
},
expandRows: true,
resourceAreaWidth: '10%',
resourceAreaHeaderContent: 'Rooms',
resourceOrder: 'type1', // to set the displayorder of resources
resources: [
{ id: '1', title: 'R1' , eventColor: 'blue', type1:10},
{ id: '2', title: 'R2', eventColor: 'green',type1:13 },
{ id: '3', title: 'R3', eventColor: '#F39C12',type1:14 },
{ id: '4', title: 'R4', eventColor: 'red' ,type1:11 },
{ id: '5', title: 'R5', eventColor: '#8E44AD',type1:12 },
],
events :'load.php',
selectable:true,
selectHelper:true,
//---------------------------ADD EVENTS----------------------------------------///
select: function(info) {
var st_time = info.startStr;
var start =st_time.split("T").join(" ");
var end_time = info.endStr;
var end =end_time.split("T").join(" ");
var resourc =info.event._def.resourceIds;
var resourceId = resourc.toString();
$('#ModalAdd').modal('show');
$('#ModalAdd #Room').val(resourceId);
$('#ModalAdd #start').val(start);
$('#ModalAdd #end').val(end);
},
eventResize:function(info)
{
var resourc =info.event._def.resourceIds;
var resourceId = resourc.toString();
var title = info.event.title;
var start =info.event.start;
var end =info.event.end;
var id = info.event.id;
var scriptUrl = "DragEvent.php";
$.ajax({
url:scriptUrl,
type:"POST",
data:{title:title, start:start, end:end, id:id, resourceId:resourceId},
success: function(data){
alert('Event updated');
calendar.refetchEvents();---------Here, its working well
}
})
},
});
calendar.render();
});
function saveData()
{
var Room= document.getElementById("Room").value;
var EventName= document.getElementById("EventName").value;
var start=document.getElementById("start").value;
var end=document.getElementById("end").value;
var ScriptUrl="addEvent.php";
$.ajax({
url:ScriptUrl,
type:"POST",
data:{EventName:EventName, start:start, end:end},
success: function(data){
alert("Added successfully");
// calendar.refetchEvents();-----------------------tried here. Not working
}
});
$('#ModalAdd').modal('hide');
calendar.refetchEvents();----------Here also, Not working
}
</script>
<style>
html, body {
overflow: hidden; /* don't do scrollbars */
font-family: Arial, Helvetica Neue, Helvetica, sans-serif;
font-size: 14px;
}
#calendar-container {
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
}
.fc-header-toolbar {
padding-top: 1em;
padding-left: 1em;
padding-right: 1em;
}
</style>
</head>
<body>
<!-- Modal -->
<div class="modal fade" id="ModalAdd" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<form class="form-horizontal" method="POST" action="pages/calenderpages/addEvent.php" name="add_item" id ="add_item">
<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"><b>Add events</b></h4>
</div>
<div class="modal-body">
<div class="form-group">
<input type="hidden" name="Room" class="form-control" id="Room" value="">
<label for="genryo" class="col-sm-4 control-label">Event name</label>
<div class="col-sm-8">
<input type="text" name="EventName" class="form-control" id="EventName" value="">
</div>
</div>
<div class="form-group">
<label for="start" class="col-sm-4 control-label">Start</label>
<div class="col-sm-8">
<input type="text" name="start" class="form-control" id="start" readonly>
</div>
</div>
<div class="form-group">
<label for="end" class="col-sm-4 control-label">End</label>
<div class="col-sm-8">
<input type="text" name="end" class="form-control" id="end" readonly>
</div>
</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" onclick="saveData()">SAVE</button>
</div>
</form>
</div>
</div>
</div>
<!------------------------------------------>
<div id='calendar-container'>
<div id='calendar'></div>
</div>
</body>
</html>
Here is my other codes:
/-----------------------Load.php------------------------------//
<?php
require_once('../../common/conn_check.php');
require_once('../../common/common.php');
$data=array();
$query ="SELECT * FROM event_schedule ";
$statement = pg_query($conn,$query);
$result = pg_fetch_all($statement);
foreach($result as $row)
{
$data[] = array(
'id' => $row["id"],
'resourceId' => $row["Room"],
'title' =>$row["EventName"],
'start' => $row["StartTime"],
'end' => $row["EndTime"]
);
}
echo json_encode($data);
?>
/---------------AddEvents.php-------------------//
<?php
require_once('../../common/conn_check.php');//for using the mysql connection
require_once('../../common/common.php');//common function
if (isset($_POST['start']) && isset($_POST['end'])){
$EventName = $_POST['EventName'];
$Room = $_POST['Room'];
$start = $_POST['start'];
$end = $_POST['end'];
$sql="INSERT INTO event_schedule
(Room,EventName, StartTime,EndTime)
VALUES
('$EventName','$Room','$start', '$end')";
$result = pg_query($conn,$sql);
echo json_encode(array('success'=>true));
}
?>
I have been trying this for weeks, I lost my confidence due to this. As a beginner, I couldn't figure out what's going wrong. Someone, please help.

The simplest option here is to make calendar global so it's accessible in all scopes.
e.g.
<script>
var calendar; //global variable
document.addEventListener('DOMContentLoaded', function() {
var calendarEl = document.getElementById('calendar');
calendar = new FullCalendar.Calendar(calendarEl, { //don't re-declare it here, just assign it
///...etc
But global variables are usually not best practice - it can lead to other issues if you're not careful. So another option is to stop using an inline event handler to trigger saveData, and instead add an event handler inside the DOMContentLoaded block, where of course calendar is already in scope. You make saveData return a Promise from the AJAX call, and then in the event handler you attach a .done() callback to it, and in there you can call refetchEvents.
So in this version, your button would become
<button type="button" class="btn btn-primary" id="savedata">SAVE</button>
and saveData() would become:
function saveData()
{
var Room = document.getElementById("Room").value;
var EventName = document.getElementById("EventName").value;
var start = document.getElementById("start").value;
var end = document.getElementById("end").value;
var promise = $.ajax({
url: "addEvent.php",
type:"POST",
data:{ EventName: EventName, start:start, end: end },
});
$('#ModalAdd').modal('hide');
return promise;
}
And lastly in the DOMContentLoaded area:
document.addEventListener('DOMContentLoaded', function() {
//....everything which is already there....and then...
$("#savedata").click(function() {
var promise = saveData();
promise.done(function(data) {
calendar.refetchEvents();
});
});
});
Although it looks like more work, this is a much better structured version than using a global variable.

Related

Send data only related to that line

I have the following dynamically generated form:
var data = [
{Id: "1", },
{Id: "2", },
{Id: "3", },
{Id: "4", },
{Id: "5", },
{Id: "6", },
];
$(document).on('click', '.dad-pagamento', function() {
var linha = ``;
for (var x = 0; x < data.length; x++) {
linha += `<form method="POST" action="" enctype="multipart/form-data" class="row g-3 instarefa">
<div class="col-2">
<input type="text" class="form-control" name="id_tareff[]" value="${data[x].Id}">
</div>
<div class="col-7">
<label for="obsposic" class="form-label">Observações </label>
<textarea rows="3" class="form-control aarea" name="obsposic[]"></textarea>
</div>
<div class="col-1">
<button type="button" class="btn-wide btn btn-primary" onclick="reg_tarefa();"> TRATADO <i class="metismenu-icon pe-7s-paper-plane"></i></button>
</div>
</form>
<hr class="linha"/>`;
$(".pagmfalta").html(linha);
$('#minhaDiv1').show();
}
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/css/select2.min.css" rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/pixeden-stroke-7-icon#1.2.3/pe-icon-7-stroke/dist/pe-icon-7-stroke.min.css" rel="stylesheet">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/js/select2.min.js"></script>
<button type="button" class="btn btn-info dad-pagamento" style="float: right; margin-right: 5%; margin-top: 4%;"><i class="metismenu-icon pe-7s-search"></i> Consultar </button>
<section id="s1">
<div style="display:none" id="minhaDiv1">
<div class="row pagmfalta">
</div>
</div>
</section>
So far so good. My problem is now sending the values ​​to php to insert in the database. I'm doing it like this:
function reg_tarefa()
{
var id_tareff = [];
$("input[name='id_tareff[]']").each(function() {id_tareff.push(this.value)});
var obsposic = [];
$("textarea[name^='obsposic[]']").each(function() {obsposic.push($(this).val())});
var dadosajax = {
'id_tareff[]' : id_tareff,
'obsposic[]' : obsposic
}
$.ajax({
url: 'regtarefa.php',
type: 'POST',
cache: false,
data: dadosajax,
success: function(result2){
}
});
}
For example, I want to click on the second button, where Id=2 and only send data regarding that id. And as I am doing it sends the data of all the ids. Can you help?
Change the button to pass itself as the argument to reg_tarefa: onclick="reg_tarefa(this);".
Then change the function to use DOM navigation relative to the button to find the inputs in the same form.
function reg_tarefa(element) {
let form = $(element).closest("form");
var id_tareff = [];
form.find("input[name='id_tareff[]']").each(function() {
id_tareff.push(this.value)
});
var obsposic = [];
form.find$("textarea[name^='obsposic[]']").each(function() {
obsposic.push($(this).val())
});
var dadosajax = {
'id_tareff[]': id_tareff,
'obsposic[]': obsposic
}
$.ajax({
url: 'regtarefa.php',
type: 'POST',
cache: false,
data: dadosajax,
success: function(result2) {
}
});
}

change style through checkbox

I'm working ona fullcalendar project.
I have these 2 checkboxes (Ore Personali e Assenze), when they are checked they should hide the events but at the moment they are not doing it.
This is my input checkbox:
<input type="checkbox" id="OP" name="calendario" value="OP">
And this is the function i've build so far:
$(document).ready(function() {
$('input[type="checkbox"]').click(function() {
var checkBox = document.getElementById("OP");
var x = document.getElementsByClassName("fc-event-container");
if (checkBox.checked === true){
x.style.visibility = "visible !important";
}else{
x.style.visibility = "hidden !important";
}
})
})
I build it by looking on the internet cause i'm new to JS and dont know much, just basic stuff.
And it's giving error in the x.style part (telling me is undefined).
Can someone explain to me how i should do it, cause on internet i only found this way and some other who's just giving me errors anyway.
thanks in advances whos gonna help me (or at least try)
i did as #Cypherjac suggest and it worked.
But now it just hide the events on the current month, when i change months i have to checked and unchecked to hide. Even if i go back to the month i hid the events they are visible
Is there a way to let them stay hide even if i change month?
Before i update the code i will specify that this is not my code, my fullcalendar is from a template i found on internet, i add the function i needed but most of th stuff was already there:
calendar.js code:
key: 'handleFullcalendar',
value: function handleFullcalendar() {
var myOptions = {
header: {
left: 'today',
center: 'prev,title,next',
right: 'none',
},
buttonText:{
today: 'Oggi',
month: 'Mese',
week: 'Settimana',
day: 'Giorno'
},
locale:'it',
allDaySlot: false,
selectable: true,
selectHelper: true,
timeFormat: 'H(:mm)',
editable: true,
eventLimit: true,
resourceAreaHeaderContent: 'Calendari',
resources: [
{
id: 'a',
title: 'Ore Personali'
},
{
id: 'b',
title: 'Assenze'
}
],
windowResize: function windowResize(view) {
var width = $(window).outerWidth();
var options = Object.assign({}, myOptions);
options.events = view.calendar.clientEvents();
options.aspectRatio = width < 667 ? 0.5 : 1.35;
$('#calendar').fullCalendar('destroy');
$('#calendar').fullCalendar(options);
},
//_______apre modal per aggiungere nuovo evento
select: function select(event) {
$('#addNewEvent').modal('show');
$('#calendar').fullCalendar('refetchEvents',event._id)
},
//_______________ELIMINARE EVENTO TRAMITE X
eventRender: function(event, element, view) {
if (view.name == 'listDay') {
element.find(".fc-list-item-time").append("<span class='closeon'>X</span>");
} else {
element.find(".fc-content").prepend("<span class='closeon'>X</span>");
}
element.find(".closeon").on('click', function() {
var deleteMsg = confirm("Vuoi davvero eliminare " + event.title + "?");
if (deleteMsg == true) {
$.ajax({
url: 'eventi/deleteEvent.php',
type: 'POST',
data: {_id: event.idAssenza, nomeUtente: event.nomeUtente},
success: function(html){
location.reload();
}
})
$('#calendar').fullCalendar('removeEvents',event._id);
}else{
location.reload();
}
})
},
//triggherà apertura modal di #editEvent
eventClick: function eventClick(event) {
var color = event.backgroundColor ? event.backgroundColor : (0, _Config.colors)('blue', 600);
$('#editEname').val(event.title);
$('event.id').val(event.idAssenza);
$('nomeUtente').val(event.nomeUtente);
$('#editStarts').val(event.start.toISOString());
$('#editEnds').val(event.end.toISOString());
$('#editNewEvent').modal('show').one('hidden.bs.modal', function (e) {
event.title = $('#editEname').val();
event.start = $('#editStarts').val();
event.end = $('#editEnds').val();
$.ajax({
url: 'eventi/updateEvent.php',
type: 'POST',
data: {start: event.start, _id: event.idAssenza, end: event.end, title: event.title, },
success: function(html){
location.reload();
}
});
$('#calendar').fullCalendar('updateEvent', event._id);
});
},
events: {
url: 'eventi/load.php',
method:'POST'
//color: <- fare in modo che prenda i colori scelti nel modal
},
droppable: false
};
{
$(function() {
$('#OP').change(function() {
var x = $('.fc-event-container');
// Access the element using jQuery
if($(this).prop('checked')){
x.css({
'visibility': 'visible'
})
}
else {
x.css({
'visibility': 'hidden'
})
}
})
});
},
var _options = void 0;
var myOptionsMobile = Object.assign({}, myOptions);
myOptionsMobile.aspectRatio = 0.5;
_options = $(window).outerWidth() < 667 ? myOptionsMobile : myOptions;
$('#editNewEvent').modal();
$('#calendar').fullCalendar(_options);
}
Calendar.php:
<?php
require_once "config.php";
session_start();
if(!ISSET($_SESSION['nomeUtente'])){
header('location:login/login.php');
}
?>
<!DOCTYPE html>
<html class="no-js css-menubar" locale="it">
<head>
<!-- Meta Tag -->
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimal-ui">
<meta name="description" content="bootstrap material admin template">
<meta name="author" content="">
<title> Calendario | E.D. Elettronica Dedicata </title>
</head>
<body>
<div class="page">
<div class="page-aside">
<div class="page-aside-switch">
<i class="icon md-chevron-left" aria-hidden="true"></i>
<i class="icon md-chevron-right" aria-hidden="true"></i>
</div>
<div class="page-aside-inner page-aside-scroll">
<div data-role="container">
<div data-role="content">
<!--LISTA CALENDARI-->
<section class="page-aside-section">
<h5 class="page-aside-title">Lista calendari di <?php echo $_SESSION["nomeUtente"]; ?></h5>
<div class="list-group has-actions">
<div class="list-group-item" data-plugin="editlist">
<div class="list-content">
<input type="checkbox" id="OP" name="calendario" value="OP" checked>
<span class="list-text">Ore Personali</span>
</div>
</div>
<div class="list-group-item" data-plugin="editlist">
<div class="list-content">
<input type="checkbox" id="assenze" name="calendario" value="assenze">
<span class="list-text">Assenze</span>
</div>
<div class="list-editable">
</div>
</div>
</div>
</section>
</div>
</div>
</div>
</div>
<div class="page-main">
<div class="calendar-container">
<div id="calendar"></div>
<!--addEvent Dialog -->
<div class="modal fade" id="addNewEvent" aria-hidden="true" aria-labelledby="addNewEvent"
role="dialog" tabindex="-1">
<div class="modal-dialog modal-simple">
<form class="modal-content form-horizontal" action="eventi/addEvent.php" method="post" role="form">
<div class="modal-header">
<button type="button" class="close" aria-hidden="true" data-dismiss="modal">×</button>
<h4 class="modal-title">Aggiungi Assenza (<?php echo $_SESSION["nomeUtente"]; ?>)</h4>
</div>
<div class="modal-body">
<div class="form-group row" id=editColor>
<label class="form-control-label col-md-2">Tipo:</label>
<input list="assenza" name="ename" id="ename" style="margin-left: 15px;" />
<datalist id="assenza">
<option value="Normali">
<option value="Straordinarie">
<option value="Ferie">
<option value="Malattia">
<option value="Permesso">
<option value="Smart Working">
<option value="Altro">
</datalist>
<input type="hidden" name="nomeUtente" id="nomeUtente" value="<?php echo $_SESSION["nomeUtente"]; ?>">
</div>
<div class="form-group row">
<label class="col-md-2 form-control-label" for="starts">Inizio:</label>
<div class="col-md-10">
<div class="input-group">
<input type="datetime-local" class="form-control" id="starts" name="starts" data-container="#addNewEvent">
</div>
</div>
</div>
<div class="form-group row">
<label class="col-md-2 form-control-label" for="ends">Fine:</label>
<div class="col-md-10">
<div class="input-group">
<input type="datetime-local" class="form-control" id="ends" name="ends" data-container="#addNewEvent">
</div>
</div>
</div>
</div>
<div class="modal-footer">
<div class="form-actions">
<input type="submit" class="btn btn-primary" value="Aggiungi Assenza">
<a class="btn btn-sm btn-white btn-pure" data-dismiss="modal" href="javascript:void(0)">Annulla</a>
</div>
</div>
</form>
</div>
</div>
<!-- End AddEvent Dialog -->
<!-- editEvent Dialog -->
<div class="modal fade" id="editNewEvent" aria-hidden="true" aria-labelledby="editNewEvent"
role="dialog" tabindex="-1" data-show="false">
<div class="modal-dialog modal-simple">
<form class="modal-content form-horizontal" action="eventi/deleteEvent.php" method="POST" role="form">
<div class="modal-header">
<button type="button" class="close" aria-hidden="true" data-dismiss="modal">×</button>
<h4 class="modal-title">Modifica Assenza (<?php echo $_SESSION["nomeUtente"]; ?>)</h4>
</div>
<div class="modal-body">
<div class="form-group row">
<label class="form-control-label col-md-2" for="editEname">Tipo:</label>
<input list="assenza" name="editEname" id="editEname" style="margin-left: 15px;" />
<datalist id="assenza">
<option value="Normali">
<option value="Straordinarie">
<option value="Ferie">
<option value="Malattia">
<option value="Permesso">
<option value="Smart Working">
<option value="Altro">
</datalist>
<input type="hidden" name="nomeUtente" id="nomeUtente" value="<?php echo $_SESSION["nomeUtente"]; ?>">
</div>
<div class="form-group row">
<label class="col-md-2 form-control-label" for="editStarts">Inizio:</label>
<div class="col-md-10">
<div class="input-group">
<input type="datetime-local" class="form-control" id="editStarts" name="editStarts" data-container="#editNewEvent">
</div>
</div>
</div>
<div class="form-group row">
<label class="col-md-2 form-control-label" for="editEnds">Fine:</label>
<div class="col-md-10">
<div class="input-group">
<input type="datetime-local" class="form-control" id="editEnds" name="editEnds"data-container="#editNewEvent">
</div>
</div>
</div>
</div>
<div class="modal-footer">
<div class="form-actions">
<button class="btn btn-primary" data-dismiss="modal" type="button">Salva modifiche</button>
<a class="btn btn-sm btn-white btn-pure" data-dismiss="modal" href="javascript:void(0)">Annulla</a>
</div>
</div>
</form>
</div>
</div>
<!-- End EditEvent Dialog -->
</div>
</div>
</div>
</body>
</html>
This is the template i'm using it, most of the code it's there, i just update the part i'm using and modifing
Since you're already using jQuery, you can use it to access the elements instead of native js
Here $(this).prop('checked') is being used to check the checked property of the checkbox
Then when it changes, change the visibility of the element based on the current state..
NOTE: The checkbox is checked initially because the element to toggle is visible when the document loads
$(function() {
$('input[type="checkbox"]').on('change', function() {
x = $('.fc-event-container')
// Access the element using jQuery
if($(this).prop('checked')){
x.css({
'visibility': 'visible'
})
}
else {
x.css({
'visibility': 'hidden'
})
}
})
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="fc-event-container">
Toggle the checkbox to toggle me
</div>
<input type="checkbox" id="OP" name="calendario" value="OP" checked>
One thing to note about the calendar is that every time you switch the month, week or day, the events are rendered again..
So that means the events will have their default state which is visible every time you switch through the tabs
So if you want to ensure the element remains hidden you have to access the element only after it has been rendered, because rendering happens sequentially, so you cannot access the element as soon as rendering has started, because by then you can't know when it will render..
So the concept I've introduced is just using the property of the calendar which is dayRender to check when the rendering of the contents is being done, and set a timeout of half a second to return the events back to their initial state..
So that is the concept, you can read through the docs to find an event that will fire after all the rendering of the days is done and then call the function to revert back them to their visible or hidden state
Check the codepen for the working demo
Use onchange event
$(document).ready(function() {
$('#OP').change(function() {
var x = document.getElementsByClassName("fc-event-container");
if (this.checked){
x.style.visibility = "visible !important";
}else{
x.style.visibility = "hidden !important";
}
})
});

Select gets double options after submit form modal

I got a problem with a bootstrap modal form and dynamic select options.
When I open the modal, there is an input and two select options.
One select is populating the second after a user check an option from
the first select.
On the first load, the select options are working ok.
When I submit the form (with Save button) and I reopen the modal, the first select gets the correct options but the second got double options.
When I reload the page everything gets back to normal until I submit the form again.
$(document).ready(function () {
var table = $('table.setting-groups');
var table_permissions = $('table.settings-groups-permissions');
var table_permissions_edit = $('table.settings-groups-permissions-edit');
var permissions = [];
var dataArray = [];
$('#addGroupModal').on('shown.bs.modal', function (e) {
$('select#permission_category').each(function () {
var $select = $(this);
$select.empty().append('<option></option>');
$.ajax({
url: $select.attr('data-source')
}).then(function (options) {
options.map(function (option) {
var $option = $('<option>');
$option
.val(option[$select.attr('data-valueKey')])
.text(option[$select.attr('data-displayKey')]);
$select.append($option);
});
});
});
$('select#permission_category').change(function () {
var category = $('select#permission_category').val();
if (category !== '') {
$('select#permission_category_description').each(function () {
var $select = $(this);
$select.empty().append('<option></option>');
$.ajax({
url: $select.attr('data-source'),
data: {category: category}
}).then(function (options) {
options.map(function (option) {
var $option = $('<option>');
$option
.val(option[$select.attr('data-valueKey')])
.text(option[$select.attr('data-displayKey')]);
$select.append($option);
});
});
});
} else {
$('select#permission_category_description')[0].empty();
}
});
$('select#permission_category_description').change(function () {
var category = $('select#permission_category').val();
var description = $('select#permission_category_description').val();
var check = $.inArray(description, permissions) > -1;
if (!check) {
permissions.push(description);
table_permissions.DataTable().row.add({
"category": category,
"description": description
}).draw();
}
});
// Save permissions
$('form#add-group').submit(function (e) {
$('#savebtn').button('loading');
e.preventDefault();
var form = $(this);
// Push table data (permissions) to form for submit
$('<input>').attr({
type: 'hidden',
id: 'permissions',
name: 'permissions',
value: permissions
}).appendTo(form);
$.ajax({
url: form.attr('action'),
type: form.attr('method'),
data: new FormData(this),
dataType: 'json',
processData: false,
contentType: false,
success: function (data) {
$('#addGroupModal').modal('toggle');
swal(
'Επιβεβαίωση Καταχώριση',
'Η ομάδα δικαιωμάτων καταχωρήθηκε επιτυχώς',
'success'
).then(function () {
permissions = [];
dataArray = [];
form[0].reset();
$('select#permission_category_description').empty();
table_permissions.DataTable().destroy();
table.DataTable().ajax.reload();
});
},
error: function (data) {
swal(
'Αποτυχία Καταχώρισης',
data.responseText,
'error'
)
}
});
});
// Remove row when you click X
table_permissions.on('click', '.delete', function () {
table_permissions.DataTable().row('.selected').remove().draw(false);
});
});
$('#addGroupModal').on('hide.bs.modal', function (e) {
// Clean forms / select / datatables / arrays on modal close
$('select#permission_category_description').empty();
$('form')[0].reset();
table_permissions.DataTable().destroy();
permissions = [];
dataArray = [];
});
$('#editGroupModal').on('shown.bs.modal', function (e) {
var id = $(e.relatedTarget).data('id');
$.post('../../custom/json/groups.php?view', {id: id}, function (arr) {
$('input#group_name').val(arr.description);
// Get existing permissions from groups
dataArray = arr.data.map(function (value) {
return value.description;
});
});
$('select#permission_category_edit').each(function () {
var $select = $(this);
$select.empty().append('<option></option>');
$.ajax({
url: $select.attr('data-source')
}).then(function (options) {
options.map(function (option) {
var $option = $('<option>');
$option
.val(option[$select.attr('data-valueKey')])
.text(option[$select.attr('data-displayKey')]);
$select.append($option);
});
});
});
$('select#permission_category_edit').change(function () {
var category = $('select#permission_category_edit').val();
if (category !== '') {
$('select#permission_category_description_edit').each(function () {
var $select = $(this);
$select.empty().append('<option></option>');
$.ajax({
url: $select.attr('data-source'),
data: {category: category}
}).then(function (options) {
options.map(function (option) {
var $option = $('<option>');
$option
.val(option[$select.attr('data-valueKey')])
.text(option[$select.attr('data-displayKey')]);
$select.append($option);
});
});
});
} else {
$('select#permission_category_description_edit')[0].empty();
}
});
$('select#permission_category_description_edit').change(function () {
var category = $('select#permission_category_edit').val();
var description = $('select#permission_category_description_edit').val();
permissions = dataArray;
var check = $.inArray(description, permissions) > -1;
if (!check) {
permissions.push(description);
table_permissions_edit.DataTable().row.add({
"category": category,
"description": description
}).draw();
}
});
var settingGroupsPermissionsEdit = {
"destroy": true,
"processing": true,
"deferRender": true,
"responsive": true,
"select": true ,
"searching": false,
"paging": false,
"info": false,
"ordering": false,
"language": {
"url": "/custom/js/data-tables/Greek.json"
},
"ajax": "../../custom/json/groups.php?view&id=" + id,
"dataSrc": "data",
"columns": [
{data: "category", className: "text-center"},
{data: "description", className: "text-center"},
{
data: null, className: "text-center btn-actions", render: function (data, type, row) {
return '<a data-id="' + data.description + '" class="danger p-0 delete"><i class="ft-x font-medium-3 mr-2"></i></a>';
}
}
]
};
$('table.settings-groups-permissions-edit').DataTable($.extend(true, {}, settingGroupsPermissionsEdit, {}));
// Save permissions
$('form#edit-group').submit(function (e) {
$('#editbtn').button('loading');
e.preventDefault();
var form = $(this);
// Push table data (permissions) to form for submit
$('<input>').attr({
type: 'hidden',
id: 'permissions',
name: 'permissions',
value: permissions
}).appendTo(form);
$.ajax({
url: form.attr('action') + '&id=' + id,
type: form.attr('method'),
data: new FormData(this),
dataType: 'json',
processData: false,
contentType: false,
success: function (data) {
$('#editGroupModal').modal('toggle');
swal(
'Επιβεβαίωση Ενημέρωσης',
'Η ομάδα δικαιωμάτων ενημερώθηκε επιτυχώς',
'success'
).then(function () {
permissions = [];
dataArray = [];
form[0].reset();
$('select#permission_category_description_edit').empty();
table_permissions_edit.DataTable().destroy();
table.DataTable().ajax.reload();
});
},
error: function (data) {
swal(
'Αποτυχία Ενημέρωσης',
data.responseText,
'error'
)
}
});
});
// Remove row when you click X
table_permissions_edit.on('click', '.delete', function () {
var row_desc = table_permissions_edit.DataTable().rows('.selected').data().pluck('description')[0];
permissions = remove(permissions, row_desc); // remove element from posted permissions array
table_permissions_edit.DataTable().row('.selected').remove().draw();
});
});
$('#editGroupModal').on('hide.bs.modal', function (e) {
// Clean forms / select / datatables / arrays on modal close
$('select#permission_category_description_edit').empty();
$('form')[0].reset();
table_permissions_edit.DataTable().destroy();
permissions = [];
dataArray = [];
});
// Delete group
table.on('click', '.swal-delete', function () {
var id = $(this).data('id');
swal({
title: 'Διαγραφή',
text: 'Είστε σίγουρος/η οτι θέλετε να διαγράψετε την ομάδα δικαιωμάτων;',
type: 'warning',
showCancelButton: true,
confirmButtonColor: '#0CC27E',
cancelButtonColor: '#FF586B',
confirmButtonText: 'Ναι',
cancelButtonText: 'Όχι'
}).then(function (isConfirm) {
if (isConfirm) {
$.post("../../custom/json/groups.php?delete", {id: id}, function (data) {
swal(
'Επιβεβαίωση Διαγραφής',
'Η ομάδα δικαιωμάτων διαγράφηκε επιτυχώς',
'success'
).then(function () {
table.DataTable().ajax.reload();
});
});
}
}).catch(swal.noop);
});
// Remove element from an array
function remove(array, value) {
return array.filter(function (element) {
return element !== value;
});
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- BEGIN ADD GROUP MODAL-->
<div class="modal fade text-left" id="addGroupModal" role="dialog" aria-labelledby="addGroupModal" style="display: none;" aria-hidden="true">
<div class="modal-dialog modal-lg" role="document">
<div class="modal-content">
<form id="add-group" action="/custom/json/groups.php?add" method="post" class="form form-horizontal" autocomplete="off" enctype="multipart/form-data">
<div class="modal-header bg-medi white">
<h4 class="modal-title" id="addGroupModal"><i class="ft-list font-medium-3 mr-2"></i> Προσθήκη Νέας Ομάδας</h4>
</div>
<div class="modal-body mt-1">
<fieldset class="form-group floating-label-form-group row">
<label class="col-md-4 label-control mt-1" for="group_name">Όνομα Ομάδας: </label>
<div class="col-md-5">
<input type="text" id="group_name" class="form-control" name="group_name">
</div>
</fieldset>
<fieldset class="form-group floating-label-form-group row">
<label class="col-md-4 label-control" for="permission_category">Κατηγορία</label>
<div class="col-md-5">
<select id="permission_category" name="permission_category" class="form-control"
data-source="/custom/json/groups.php?permission-category"
data-valueKey="category"
data-displayKey="category">
</select>
</div>
</fieldset>
<fieldset class="form-group floating-label-form-group row">
<label class="col-md-4 label-control" for="permission_category_description">Πρόσβαση</label>
<div class="col-md-5">
<select id="permission_category_description" name="permission_category_description" class="form-control"
data-source="/custom/json/groups.php?permission-description"
data-valueKey="description"
data-displayKey="description">
</select>
</div>
</fieldset>
<div class="table-responsive">
<table class="table table-condensed table-bordered table-sm base-style table-hover full-width settings-groups-permissions">
<thead class="bg-medi text-white text-center">
<tr>
<th>Κατηγορία</th>
<th>Πρόσβαση</th>
<th></th>
</tr>
</thead>
</table>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Κλείσιμο</button>
<button type="submit" class="btn btn-medi white" id="savebtn" data-loading-text="Αποθήκευση...">Αποθήκευση</button>
</div>
</form>
</div>
</div>
</div>
<!-- END ADD GROUP MODAL-->
<!-- BEGIN EDIT GROUP MODAL-->
<div class="modal fade text-left" id="editGroupModal" role="dialog" aria-labelledby="editGroupModal" style="display: none;" aria-hidden="true">
<div class="modal-dialog modal-lg" role="document">
<div class="modal-content">
<form id="edit-group" action="/custom/json/groups.php?edit" method="post" class="form form-horizontal" autocomplete="off" enctype="multipart/form-data">
<div class="modal-header bg-medi white">
<h4 class="modal-title" id="editGroupModal"><i class="ft-list font-medium-3 mr-2"></i> Επεξεργασία Ομάδας</h4>
</div>
<div class="modal-body mt-1">
<fieldset class="form-group floating-label-form-group row">
<label class="col-md-4 label-control mt-1" for="group_name">Όνομα Ομάδας: </label>
<div class="col-md-5">
<input type="text" id="group_name" class="form-control" name="group_name" disabled>
</div>
</fieldset>
<fieldset class="form-group floating-label-form-group row">
<label class="col-md-4 label-control" for="permission_category_edit">Κατηγορία</label>
<div class="col-md-5">
<select id="permission_category_edit" name="permission_category" class="form-control"
data-source="/custom/json/groups.php?permission-category"
data-valueKey="category"
data-displayKey="category">
</select>
</div>
</fieldset>
<fieldset class="form-group floating-label-form-group row">
<label class="col-md-4 label-control" for="permission_category_description_edit">Πρόσβαση</label>
<div class="col-md-5">
<select id="permission_category_description_edit" name="permission_category_description" class="form-control"
data-source="/custom/json/groups.php?permission-description"
data-valueKey="description"
data-displayKey="description">
</select>
</div>
</fieldset>
<div class="table-responsive">
<table class="table table-condensed table-bordered table-sm base-style table-hover full-width settings-groups-permissions-edit">
<thead class="bg-medi text-white text-center">
<tr>
<th>Κατηγορία</th>
<th>Πρόσβαση</th>
<th></th>
</tr>
</thead>
</table>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Κλείσιμο</button>
<button type="submit" class="btn btn-medi white" id="editbtn" data-loading-text="Αποθήκευση...">Αποθήκευση</button>
</div>
</form>
</div>
</div>
</div>
<!-- END EDIT GROUP MODAL-->
Any suggestions ? I can't find where is the issue that causes js to run twice on select populate options.
Thank you in advance
UPDATE: The 2nd select option is doubled on modal show not on form submit.
Because you bind $('select#permission_category').change inside $('#addGroupModal').on('shown.bs.modal' handler so each time your modal show, it will bind $('select#permission_category').change another time. That's why when you open the modal second time, the 2nd select option is doubled and will be tripled on third time...
You can solve it by:
Option 1: Move $('select#permission_category').change to be outside of $('#addGroupModal').on('shown.bs.modal' handler.
Option 2: Remove $('select#permission_category') change handler using .off() when closing modal or before bind it in $('#addGroupModal').on('shown.bs.modal' handler.
Option 3: Create all options first then use .html() instead of .append() to set the html contents of select (this still bind change multiple time but the options is not multipled)

Add Event to Calendar in fullcalendar

I have a problem again and do not really get on with it.
I would like to know that you can enter an appointment and I already have the following script.
Unfortunately, no entries are entered in the calendar :-( can someone help me there?
I've already asked quite a bit about google and co. Unfortunately, I come to no real point of help.
can it be that I already use the eventRender and then want to use it again below?
here once my code:
<link rel='stylesheet' href='kalender2/fullcalendar.css' />
<script src='kalender2/fullcalendar.js'></script>
<script src='kalender2/locale/de.js'></script>
<script src="js/bootstrap.min.js"></script>
<script src="js/bootstrap.bundle.min.js"></script>
<script src="kalender2/lib/hour.js"></script>
<script>
var CalenderEvent;
var datenPruefenDatenSenden;
var terminPruefenDatenSenden;
var datenPruefenDatenVerarbeiten;
var termin_nachberechnung;
var TerminAddZeit;
var AddEventToCalener;
$(document).ready(function() {
function DeleteEvent(id){
SendFormData(id,'',"delete");
$('#calendar').fullCalendar('removeEvents',id);
}
var initialLocaleCode = 'de';
$('#calendar').fullCalendar({
header: {
left: 'prev,next today',
center: 'title',
right: 'month,agendaWeek,agendaDay,listWeek'
},
dayClick: function(date, jsEvent, view) {
$('#calenderAdEvent').modal('show');
$('#start_date_add_day').val(date.format('DD.MM.YYYY'));
$('#start_date_add_time').val(date.format('HH:mm'));
},
eventRender: function(eventObj, $el) {
$el.popover({
title: eventObj.title,
content: eventObj.description,
trigger: 'hover',
placement: 'top',
container: 'body'
});
$el.html(eventObj.title + '<span class="removebtn" onclick="DeleteEvent('+eventObj.id+');" id="Delete">X</span>');
$el.find(".removebtn").click(function() {
$('#calendar').fullCalendar('removeEvents',eventObj.id);
});
},
businessHours: [
<?php echo $Offen;?>
],
eventDrop: function( event, delta, revertFunc, jsEvent, ui, view ) {
var Alertback = SendFormData(event.id,$.fullCalendar.moment(event.start._d), $.fullCalendar.moment(event.end._d),"update");
alert(Alertback);
},
eventResize: function( event, delta, revertFunc, jsEvent, ui, view ) {
var Alertback = SendFormData(event.id,$.fullCalendar.moment(event.start._d), $.fullCalendar.moment(event.end._d),"update");
alert(Alertback);
},
timezone: 'Europe/Berlin',
nowIndicator: true,
now: '<?php echo date("Y-m-d", time() ) .'T'. date("H:i:s");?>',
locale: 'de',
buttonIcons: true, // show the prev/next text
defaultView: 'agendaWeek',
defaultDate: '<?php echo date("Y-m-d", time() );?>',
navLinks: true, // can click day/week names to navigate views
editable: true,
eventLimit: true, // allow "more" link when too many events
allDaySlot: true,
droppable: true,
events: [
<?php echo $aus;?>
],
timeFormat: 'H(:mm)',
eventClick: function(event, jsEvent, view) {
CalenderEvent = event;
$('#id_termin').val(event.id);
$('#name').val(event.title);
$('#Time_Event').val(event.TimeEvent);
$('#description').val(event.description);
$('#start_date_day').val(moment(event.start).format('DD.MM.YYYY'));
$('#start_date_time').val(moment(event.start).format('HH:mm'));
if(event.end) {
$('#end_date_day').val(moment(event.end).format('DD.MM.YYYY'));
$('#end_date_time').val(moment(event.end).format('HH:mm'));
} else {
$('#end_date_day').val(moment(event.end).format('DD.MM.YYYY'));
$('#end_date_time').val(moment(event.end).format('HH:mm'));
}
$('#event_id').val(event.id);
$('#calenderEditEvent').modal();
}
});
datenPruefenDatenSenden = function(){
var start = $('#start_date_day').val()+'//'+$('#start_date_time').val();
var end = $('#end_date_day').val()+'//'+$('#end_date_time').val();
var erg = SendFormData($("#id_termin").val(),start,end,'TerminEditSave');
$('#calenderEditEvent').modal('hide');
CalenderEvent.start = moment($('#start_date_day').val()+' '+$('#start_date_time').val(), "DD.MM.YYYY HH:MM");
CalenderEvent.end = moment($('#end_date_day').val()+' '+$('#end_date_time').val(), "DD.MM.YYYY HH:MM");
$('#calendar').fullCalendar('updateEvent', CalenderEvent);
}
datenPruefenDatenVerarbeiten = function (daten){
if(daten == 1){$('#submit_erg').html('<div class="alert alert-danger">Terminüberschneidung</div><button class="btn btn-info" onclick="terminPruefenDatenSenden();">Erneut prüfen</button>');}
$('#submit_button').html('<button type="button" class="btn btn-warning" onclick="datenPruefenDatenSenden();">Termin Speichern</button>');
}
terminPruefenDatenSenden = function (){
$('#submit_erg').html('');
var start = $('#start_date_day').val()+'//'+$('#start_date_time').val();
var end = $('#end_date_day').val()+'//'+$('#end_date_time').val();
var erg = SendFormData($("#id_termin").val(),start,end,'pruefen');
}
termin_nachberechnung = function (){
var TimePlus = new Hour($('#Time_Event').val());
var zeit = new Hour($('#start_date_time').val()+':00');
$('#end_date_time').val(zeit.add(TimePlus));
}
TerminAddZeit = function (){
var erg = SendFormData($("#id_termin_add").val(),$('#start_date_add_time').val(),'','TimePlus');
$('#start_date_add_time_end').val(erg);
}
AddEventToCalener = function(){
var Start = moment($('#start_date_add_day').val()+' '+$('#start_date_add_time').val(), "DD.MM.YYYY HH:MM");
var End = moment($('#start_date_add_day').val()+' '+$('#start_date_add_time_end').val(), "DD.MM.YYYY HH:MM");
var event = new Object();
event = {
title: 'Testtermin',
start: Start,
end: End,
allDay: false,
};
console.log(event);
$('#calendar').fullCalendar('renderEvent', event);
}
});
$(function() {
$('[data-toggle="datepicker_bearbeiten"]').datepicker({
autoHide: true,
format: 'dd.mm.yyyy',
zIndex: 2048,
});
});
function SendFormData(id,start,end,aufruf){
var erg;
if(aufruf == 'update'){start = start/1000;end = end/1000;}
$.ajax({type: "post",url: "kalender2/kalender.class.php",data : {id : id,sta : start,end : end,aufruf : aufruf}
}).done(function( dataEnd ){if(aufruf == 'pruefen'){datenPruefenDatenVerarbeiten(dataEnd);}erg = dataEnd;});
return erg;
}
</script>
<div id='calendar'></div>
<div class="modal" id="calenderAdEvent" tabindex="-1" role="dialog">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Termin eintragen</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div class="input-group mb-3">
<div class="input-group-prepend">
<span class="input-group-text">Datum</span>
</div>
<input type="text" id="start_date_add_day" name="start_date_add_day" class="form-control">
</div>
<div class="input-group mb-3">
<div class="input-group-prepend">
<span class="input-group-text">Dienstleistung</span>
</div>
<select class="custom-select" id="id_termin_add">
<option selected>bitte wählen</option>
<?php echo $dienst;?>
</select>
</div>
<div class="input-group mb-3">
<div class="input-group-prepend">
<span class="input-group-text">Termin von</span>
</div>
<input type="text" id="start_date_add_time" name="start_date_add_time" class="form-control">
<div class="input-group-append">
<span class="input-group-text">-</span>
</div>
<input type="text" name="start_date_add_time_end" id="start_date_add_time_end" class="form-control">
</div>
<div class="input-group mb-3">
<div class="input-group-prepend">
<span class="input-group-text">Kundenname</span>
</div>
<input type="text" list="kunden" id="KundenName" name="KundenName" class="form-control" onkeyup="KundenListe();">
<datalist id="kunden">
<?php echo $KundenListe;?>
</datalist>
<div class="input-group-append">
<span class="input-group-text">oder KN</span>
</div>
<input type="text" name="KIDTerminBuchen" id="KIDTerminBuchen" class="form-control">
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary" onclick="AddEventToCalener();">Save changes</button>
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<div class="modal" id="calenderEditEvent" tabindex="-1" role="dialog">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Termin bearbeiten</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div class="input-group mb-3">
<div class="input-group-prepend">
<span class="input-group-text" id="basic-addon1">Start</span>
</div>
<input type="text" name="termin" id="start_date_day" class="form-control" data-toggle="datepicker_bearbeiten">
<input type="text" id="start_date_time" onkeyup="termin_nachberechnung('Hallo');" class="form-control datetimepicker-input" data-target="#datetimepicker3" data-target-input="nearest"/>
<div class="input-group-append">
<span class="input-group-text">
<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABkAAAAZCAYAAADE6YVjAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAHfSURBVEhLzZW9L91hFMcvaby0HUi9VKJNE2ZbvWxERQdTO5h0YLCQWLAykehUJAYWIWZSjBJtojqQog1TUyotwl8g+HyfU7fXffm9Mfgkn+ScJzf3/J7n+Z3zi90HHuBrnMBveITneIhfcRhrMDJvcA8/Yw9W4RPMxqdYiwP4A1cwVLFcnMYNrNdCAtrZOwvjqGgb7mOfFvzIwU84g3laSOI5/rIwhTJcw1GXeaAdqECWy1LxKiIeok6gy2VpeIubmG4H1/gVEeX4FytcloDOehcbXJaZIEWE7mbOwv/oNV210JOgRXQap1jisn+oD/Sa+hG0iJjFDguNLVQf+BGmiApMWmgcoxrNDz3dBfa7zJsmXLbQ0KhQU3mhJlWBS9zWgg/VqL6J8wdLLcxIJ+p3O9iqBR9acN5CYx01izKhAj/xhcuCoYYct9AYwkELU4hSQHxEDdk4Or/vmHwvypcwbIFiPMPHLktA4zp5wkblA45YeBPtRuNa0/Q26G41uwpdloZe/IKPXBYeNetvbHSZB2Oocf3MZcGpwwO8MUq80Oun77l2lq8FD4pQD6bv/isthKESNa5PUB+ydmzGl6hG68ZF1LR9jwUYGY1rHcEU6k/VuAuoRlMfRL2/uyQWuwKiRlWN6WWKKwAAAABJRU5ErkJggg==">
</span>
</div>
</div>
<div class="input-group mb-3">
<div class="input-group-prepend">
<span class="input-group-text" id="basic-addon1">Ende</span>
</div>
<input type="text" name="termin" id="end_date_day" class="form-control" data-toggle="datepicker_bearbeiten">
<input type="text" id="end_date_time" class="form-control datetimepicker-input" data-target="#datetimepicker3" data-target-input="nearest"/>
<div class="input-group-append">
<span class="input-group-text">
<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABkAAAAZCAYAAADE6YVjAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAHfSURBVEhLzZW9L91hFMcvaby0HUi9VKJNE2ZbvWxERQdTO5h0YLCQWLAykehUJAYWIWZSjBJtojqQog1TUyotwl8g+HyfU7fXffm9Mfgkn+ScJzf3/J7n+Z3zi90HHuBrnMBveITneIhfcRhrMDJvcA8/Yw9W4RPMxqdYiwP4A1cwVLFcnMYNrNdCAtrZOwvjqGgb7mOfFvzIwU84g3laSOI5/rIwhTJcw1GXeaAdqECWy1LxKiIeok6gy2VpeIubmG4H1/gVEeX4FytcloDOehcbXJaZIEWE7mbOwv/oNV210JOgRXQap1jisn+oD/Sa+hG0iJjFDguNLVQf+BGmiApMWmgcoxrNDz3dBfa7zJsmXLbQ0KhQU3mhJlWBS9zWgg/VqL6J8wdLLcxIJ+p3O9iqBR9acN5CYx01izKhAj/xhcuCoYYct9AYwkELU4hSQHxEDdk4Or/vmHwvypcwbIFiPMPHLktA4zp5wkblA45YeBPtRuNa0/Q26G41uwpdloZe/IKPXBYeNetvbHSZB2Oocf3MZcGpwwO8MUq80Oun77l2lq8FD4pQD6bv/isthKESNa5PUB+ydmzGl6hG68ZF1LR9jwUYGY1rHcEU6k/VuAuoRlMfRL2/uyQWuwKiRlWN6WWKKwAAAABJRU5ErkJggg==">
</span>
</div>
</div>
<input type="hidden" id="id_termin">
<input type="hidden" id="Time_Event">
</div>
<div class="modal-footer">
<span id="submit_erg"></span>
<span id="submit_button"><button type="button" class="btn btn-info" onclick="terminPruefenDatenSenden();">Prüfen</button></span>
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
I have done some more tests. As soon as I take the eventRender: function (eventObj, $ el) { ........ }, out, I use the function AddEventToCalener = function () { $ ('# calendar'). fullCalendar ('renderEvent', { title: 'dynamic event', start: '2018-11-26', allDay: true }); } successfully.
But as soon as I insert eventRender again, I get the following message:
Error: TOOLTIP: Option "content" provided type "undefined" but
expected type "(string | element | function)"
So the problem is still that the event is not entered in the calendar. the console gives me the following with console.log
{…} ​ allDay: false ​ end: Object { _isAMomentObject: true, _i: "26.11.2018 12:00", _f: "DD.MM.YYYY HH:MM", … } ​ start: Object { _isAMomentObject: true, _i: "26.11.2018 11:30", _f: "DD.MM.YYYY HH:MM", … } ​ title: "Testtermin" ​ <prototype>: Object { … }
Your code is failing to add the event because of a missing field.
In the eventRender function you create a popover, and the popover tries to read a property called "description" from the event:
content: eventObj.description
However, your AddEventToCalener() function defines an event like this:
event = {
title: 'Testtermin',
start: Start,
end: End,
allDay: false,
};
In this event there is no "description" field specified. This means it's undefined, and therefore when eventRender runs and tries to create the popover, it crashes because it can't read that field. (I know this from the error message - it appears the popover code is programmed to check the type of the value given in the "content" option, and will only accept strings, HTML elements, or functions - it will not accept undefined variables.)
For the eventRender/popover code to work you need to specify something for the field, even if it's just an empty string:
event = {
title: 'Testtermin',
start: Start,
end: End,
allDay: false,
description: ""
};
Also, your momentJS parsing string is incorrect - instead of
"DD.MM.YYYY HH:MM"
it should be
"DD.MM.YYYY HH:mm"
because MM signifies months, whereas mm signifies minutes. See http://momentjs.com/docs/#/parsing/string-format/ for documenation.
Fullcalendar v5
let calendarEl = document.getElementById('calendar');
let calendar = new FullCalendar.Calendar(calendarEl, {
dateClick: function(date) {
console.log(date);
console.log(date.jsEvent);
console.log(date.view);
},
})

How do I get the modal window to pop up when I select a time slot on fullCalendar?

I have been able to get my FullCalendar plug in working on my local host and want to be able to create events through a pop up window. The following code sets up the calendar and allows me to select a time slot and I thought present the modal view to allow an entry to be made:
$(document).ready(function(){
var calendar = $('#calendar').fullCalendar({
header:
{
left: 'prev,next today',
center: 'title',
right: 'agendaDay agendaWeek month'
},
defaultView: 'agendaWeek',
slotDuration : '00:15:00',
scrollTime: '13:00:00',
minTime : '09:00:00',
maxTime : '21:00:00',
slotEventOverlap: false,
firstDay : 1,
selectable: true,
selectHelper: true,
editable:true,
//select function:
select: function(start, end, allDay){
endtime = $.fullCalendar.formatDate(end, 'h:mm tt');
starttime = $.fullCalendar.formatDate(start, 'ddd, MMM d, h:mm tt');
var mywhen = starttime + ' - ' + endtime;
$('#createEventModal #apptStartTime').val(start);
$('#createEventModal #apptEndTime').val(end);
$('#createEventModal #apptAllDay').val(allDay);
$('#createEventModal #when').text(mywhen);
$('#createEventModal').modal('show');
},
});
//function to submit the form
$('#submitButton').on('click', function(e){
//cancel the link options
e.preventDefault();
doSubmit();
});
});
function doSubmit(){
alert("form submitted");
$("#createEventModal").modal('hide');
$("#calendar").fullCalendar('renderEvent',
{
title: $('#clientName').val(),
start: new Date($('#apptStartTime').val()),
end: new Date($('#apptEndTime').val()),
allDay: ($('#apptAllDay').val() == "true"),
},
true);
}
this is my HTML code as it stands to create my modal form:
<!--call the calendar -->
<div id='calendar'></div>
<!-- form to capture appointment Data-->
<div id="createEventModal" class="modal hide" tabindex="-1" role="dialog" aria-labelledby="myModalLabel1" aria-hidden="true">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">x</button>
<h3 id="myModalLabel1">Book Appointment</h3>
</div>
<div class="modal-body">
<form id="createAppointmentForm" class="form-horizontal">
<div class="control-group">
<label class="control-label" for="inputClient">Client:</label>
<div class="controls">
<input type="text" name="clientName" id="clientName" placeholder="name here"
tyle="margin: 0 auto;" data-provide="typeahead" data-items="4" data-source="[
"Value 1","Value 2","Value 3"]">
<input type="hidden" id="apptStartTime"/>
<input type="hidden" id="apptEndTime"/>
<input type="hidden" id="apptAllDay"/>
</div>
</div>
<div class="control-group">
<label class="control-label" for="when">When:</label>
<div class="controls controls-row" id="when" style="margin-top:5px;">
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" data-dismiss="modal" aria-hidden="true" class="btn">Cancel</button>
<button type="submit" id="submitButton" class="btn btn-primary">Save Appointment</button>
</div>
</div>
I don't know what I am missing to get the form to present to user. I am new to web development and would really appreciate some help with this
Try using the jQuery UI Dialog widget. For what you want, you might need some code like the following.
$(".modal-body").dialog({
title: "Book Appointment",
modal: true,
buttons: {
"Save Appointment": function() {
//appt save code here
},
Cancel: function() {
$(this).dialog("close");
}
}
});

Categories