FullCalendar - Changing hidden days with jQuery - javascript

I'm filtering my calendar, I change the start and end date, status of my events, and other stuffs. I do that with:
$("body").on("click", "#btnFiltrar", function() {
fechaIni = $("#fechaIni").val();
fechaFin = $("#fechaFin").val();
cp = $("#txtCP").val();
var events = {
url: "./php/xxxxxxxx.php",
type: "POST",
data: {
fechaIni: fechaIni,
fechaFin: fechaFin,
cp: cp,
provincia: provincia,
...
}
}
$("#calendar").fullCalendar("removeEventSource", events);
$("#calendar").fullCalendar("addEventSource", events);
$("#calendar").fullCalendar("refetchEvents");
});
It works fine. But when I want to change the variable hiddenDays dynamically, I can't make it work!
I add to my code this:
(By default this variables are global)
var dias = ["0","1","2","3","4","5","6"];
var ocultarDias = []; // is empty because it shows all days
// inside click button
diasSeleccionados = $("#selDias").val(); // returns array eg: ["1","2","3","4","5"]
ocultarDias = $(dias).not(diasSeleccionados).get(); // compare 2 arrays and get the difference
So, with that and the call fullcalendar with the attribute:
function llenarCalendario() {
$("#calendar").fullCalendar({
lang: 'es',
firstDay: 1,
hiddenDays: ocultarDias,
...
});
}
I miss something? I want to do this without reload the page, just call again the function or, as the function on click button, refetchEvents or something like that. Is possible?

You can recreate the calendar and add the events, which you have already have, again with the following method.
function reloadCalendar(){
//Get all events in a array
var events = $("#calendar").fullCalendar( 'getEventSources' );
$("#calendar").fullCalendar( 'destroy' ); // Destroy the calendar
$("#calendar").fullCalendar({ //Recreate the calendar with the hidden days
hiddenDays: [ 2, 4 ]
});
//With JavaScript
events.forEach(function(event) { //Restore all events
$("#calendar").fullCalendar( 'addEventSource', event);
});
//With jQuery
var jEvents = $.makeArray(events);
$(jEvents).each(function( i ) {
$("#calendar").fullCalendar( 'addEventSource', events[i]);
});
}
Now you simply can call the method. I hope it was helpful.

var newhiddendays = [0, 6]; // show Mon-Fr (hide Sat/Sun)
$('#calendar').fullCalendar('option', 'hiddenDays', newhiddendays);

You have to use it with optionmethod in order to set new options for your calendar
https://fullcalendar.io/docs/utilities/dynamic_options/
function llenarCalendario() {
$("#calendar").fullCalendar('option',{
lang: 'es',
firstDay: 1,
hiddenDays: ocultarDias,
...
});
}

I finally found a way to do that without reload the page. With the help of #todes using 'options' and adding the three lines below that.
Very important: the array of hiddenDays must be an array of ints.
var dias = ["0","1","2","3","4","5","6"];
var ocultarDias = []; // is empty because it shows all days
$(document).ready(function () {
llenarCalendario();
$("body").on("click", "#btnFiltrar", function() {
fechaIni = $("#fechaIni").val();
fechaFin = $("#fechaFin").val();
cp = $("#txtCP").val();
var diasSeleccionados = $("#selDias").val(); // select multiple, returns array eg: ["1","2","3","4","5"]
ocultarDias = $(dias).not(diasSeleccionados).get(); // compare 2 arrays and get the difference
ocultarDias = ocultarDias.map(Number); // array of strings to int for fullcalendar to work
var events = {
url: "./php/xxxxxxxxxx.php",
type: "POST",
data: {
fechaIni: fechaIni,
fechaFin: fechaFin,
cp: cp
}
}
$("#calendar").fullCalendar('option', {
hiddenDays: ocultarDias
});
$("#calendar").fullCalendar("removeEventSource", events);
$("#calendar").fullCalendar("addEventSource", events);
$("#calendar").fullCalendar("refetchEvents");
});
});
function llenarCalendario() {
$("#calendar").fullCalendar({
lang: 'es',
firstDay: 1,
hiddenDays: ocultarDias,
...
});
}

Related

Parameters .replace() twice jQuery plugin doesn't works

I'm writing a jQuery Plugin with parameters but I don't manage to set two parameters.
jsfiddle
(function($) {
$.fn.ototypo = function(options) {
var defauts = {
'aaa': true, // ON/OFF ponctuation
'bbbccc': true // ON/OFF parenthese
};
var parametres = $.extend(defauts, options);
return this.each(function() {
var aaa = $(this).html().replace(/a/g, "aaa");
var bbbccc = $(this).html().replace(/b/g, "bbb").replace(/c/g, "ccc");
if (parametres.aaa) {
$(this).html(aaa)
}
if (parametres.bbbccc) {
$(this).html(bbbccc)
}
});
};
})(jQuery);
$('p').ototypo();
In this example I've two functions, one changing a to aaa and the other changing b to bbb and c to ccc, I would like to be able to enable both fonction called aaa and bbbccc. If I set true to the fonctions, only the last seems to works. I need to disable one to enable the other and vice-versa.
The last call to html overwrites the previous call to html and as you only replace on the original HTML you lose the prevoius replacement etc.
(function($) {
$.fn.ototypo = function(options) {
var defauts = {
'aaa': true, // ON/OFF ponctuation
'bbbccc': true // ON/OFF parenthese
};
var parametres = $.extend(defauts, options);
return this.each(function() {
var html = $(this).html();
if (parametres.aaa) {
html = html.replace(/a/g, "aaa");
}
if (parametres.bbbccc) {
html = html.replace(/b/g, "bbb").replace(/c/g, "ccc");
}
$(this).html(html)
});
};
})(jQuery);
$('p').ototypo();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>abcdefghijklmnopqrstuvwxyz</p>
It should be noted that your approach would remove all external event handlers and any data stored by jQuery related to the elements, and it won't work with nested elements all matching the passed in selector etc.

jQuery DataTables duplicates are initially loading

So, adding on to my question from yesterday: jQuery AJAX call function on timeout
Using the first answer from the post from yesterday, the table does indeed reload without refreshing the whole page. It does so after 30 seconds.
But my problem lies before the first refresh...
The page loads, and the records are duplicated. But after the first refresh and every refresh after (unless I manually refresh using F5), everything is fine. No duplicates.
I'm trying to figure out why there are duplicates and how to remove the duplicates upon the page's initial ready event.
Here is the code, starting with the ready event:
$(document).ready(function()
{
$.ajax({
url:'api/qnams_all.php',
type:"GET",
dataType:"json"
}).done(function(response) {
console.log(response.data);
renderDataTable(response.data)
}).fail(function() {
alert( "error" );
}).always(function() {
alert( "complete" );
});
});
Here is the function to load the DataTable:
function renderDataTable(data)
{
var $dataTable = $('#example1').DataTable({
"ajax": 'api/qnams_all.php', // just added this
"data": data,
"bDestroy": true,
"stateSave": true
});
// then I add the reload function
setInterval( function () {
$dataTable.ajax.reload();
}, 30000 );
});
As stated above, the setInterval function works like how it should. It's just the initial page load is duplicating all of the records.
Does anyone see why and how to fix it?
I think you've got some duplication going on. You don't need to load the ajax flie and then load it again when you set up the DataTable.
Try replacing all of your code with this:
$(document).ready(function() {
// load and render the data
var $dataTable = $('#example1').DataTable({
"ajax": 'api/qnams_all.php', // just added this
"data": data,
"bDestroy": true,
"stateSave": true,
// the init function is called when the data table has finished loading/drawing
"init": function() {
// now that the initial data has loaded we can start the timer to do the refresh
setInterval(function() {
$dataTable.ajax.reload();
}, 30000);
}
});
});
Calling clear prevents duplicate rows while loading data into table:
$("#checkResourcesButton").click(function() {
$.post("./get/resources", {
featureName: $('#myvar').val()
}).done(function (data) {
var table = $('#table-output').DataTable();
table.clear();
var json = JSON.parse(data);
for (var row in json) {
var nameVal = json[row].Name;
var emailVal = json[row].emailId;
var roleVal = json[row].role;
var startDateVal = json[row].startDate;
var endDateVal = json[row].endDate;
var toAdd =
{
name: String(nameVal),
emailId: String(emailVal),
role: String(roleVal),
startDate: String(startDateVal),
endDate: String(endDateVal)
};
table.row.add(toAdd);
}
table.draw();
});
});

magnific passing in array

I am trying to pass in a list of images to get magnific popup to use the images however if I pass them in as their variable it does not work. I can console.log the output of the variable and paste that in place of the variable in the magnific call and it works just fine. Any ideas why passing the variable here does not work?
Here you can edit it however you must view it here to test it.
Again, you can copy the output of the console.log and paste it in place of the variable compiledList and it works just does not work as a variable.
Below is the code...
$(function(){
var urlList = ["http://img3.wikia.nocookie.net/__cb20140125162709/cartoonfatness/images/c/c0/Futurama.jpg","http://img3.wikia.nocookie.net/__cb20140125162709/cartoonfatness/images/c/c0/Futurama.jpg","http://img3.wikia.nocookie.net/__cb20140125162709/cartoonfatness/images/c/c0/Futurama.jpg"];
var compiledList = ( '{src : \'' + urlList.join('\'}, {src : \'') + '\'}' );
$('a').on('click',function(e){
e.preventDefault();
$.magnificPopup.open({
items: [compiledList],
gallery: {
enabled: true
},
type: 'image',
callbacks: {
open: function() {
console.log(compiledList);
}
}
});
});
});
What you're doing currently is making a String which when console.loged looks like an object, but it's not. Here are 2 easy options.
Just make the urlList an array of objects by wraping each url with {src: "URL"}
Use a for loop to iterate over urlList and make an array of objects. I've added this code below.
http://jsbin.com/sokidazi/2
var urlList = ["http://img3.wikia.nocookie.net/__cb20140125162709/cartoonfatness/images/c/c0/Futurama.jpg","http://img3.wikia.nocookie.net/__cb20140125162709/cartoonfatness/images/c/c0/Futurama.jpg","http://img3.wikia.nocookie.net/__cb20140125162709/cartoonfatness/images/c/c0/Futurama.jpg"],
i = 0,
l = urlList.length,
compiledList = [];
for(;i < l;i++){
compiledList.push({src: urlList[i]});
}
$('a').on('click',function(e){
e.preventDefault();
$.magnificPopup.open({
items: compiledList,
gallery: {
enabled: true
},
type: 'image',
callbacks: {
open: function() {
console.log(compiledList);
}
}
});
});

jQuery on click requires two clicks before triggering function

I have the following code which listens to a click on a.core-overlay, which then runs the overlay() function, which is part of jQueryTools.
The following works fine when the link is clicked and the function runs after only one click.
$("a.core-overlay").overlay({
target:"div.global-overlay",
mask: '#3D3D3D',
api: true,
onBeforeLoad: function() {
var toDoID = this.getTrigger().attr("id");
var toDo = toDoID.split('-');
var objectAction = toDo[0];
var objectType = toDo[1];
var objectID = toDo[2];
$('div.overlay-inner').load('/includes/functions/overlay-controls.php', {action: objectAction, type: objectType, object: objectID });
}
});
});
When I then put that in to an on click listener, it requires two clicks before it triggers the overlay function.
$(document).on('click', 'a.core-overlay', function(event) {
$(this).overlay({
target:"div.global-overlay",
mask: '#3D3D3D',
api: true,
onBeforeLoad: function() {
var toDoID = this.getTrigger().attr("id");
var toDo = toDoID.split('-');
var objectAction = toDo[0];
var objectType = toDo[1];
var objectID = toDo[2];
$('div.overlay-inner').load('/includes/functions/overlay-controls.php', {action: objectAction, type: objectType, object: objectID });
}
});
});
I need it to trigger as a live event as I use ajax to insert rows in to a table, but when the link is clicked on one of these it wouldn't trigger at all with the first piece of code, but triggers after two clicks with the second. Any ideas? I've tried so many different things without any luck.
Try changing the overlay code inside your click handler to this:
$(this).overlay({
target:"div.global-overlay",
mask: '#3D3D3D',
api: true,
load: true,
onBeforeLoad: function() {
var toDoID = this.getTrigger().attr("id");
var toDo = toDoID.split('-');
var objectAction = toDo[0];
var objectType = toDo[1];
var objectID = toDo[2];
$('div.overlay-inner').load('/includes/functions/overlay-controls.php', {action: objectAction, type: objectType, object: objectID });
}
});
Added load: true to make the overlay open immediately rather than waiting for the click.

sending value from one js function to another as parameter

Javascript newbie question
I'm fetching user input from text and use that value to send to the controller for further process. On page init everything is fine, now I want to bind OK button to send users value to my page init script (I'm trying to avoid copying script). Here's the code
#Html.ActionLink("OK", "Ajax", null, new { #class = "button", #id ="myDate" })
on page init
$(document).ready(function dataTable() {
$('#dataTable').dataTable({
"bServerSide": true,
"fnServerParams": function (aoData) {
var date = $('input[name="myDate"]').val();
aoData.push({ "name": "Date", "value": date });
});
});
on user input and clicking the button I should take that input and sent to the above script to process
$('#myDate').click(function () {
var date = $('input[name="myDate"]').val();
// ????
// Should I change first function to receive parameter as argument
});
One way is to factor out the code to get the date outside the datatable init
function getDate(){
var date = $('input[name="myDate"]').val();
return date;
}
Then in your datatable init
var date = getDate();
and the same in your click event
$('#myDate').click(function () {
var date = getDate();
});
You should end up with this
$(document).ready(function dataTable() {
function getDate(){
var date = $('input[name="myDate"]').val();
return date;
}
$('#dataTable').dataTable({
"bServerSide": true,
"fnServerParams": function (aoData) {
var date = getDate();
aoData.push({ "name": "Date", "value": date });
});
});
$('#myDate').click(function () {
var date = getDate();
});
});

Categories

Resources