Bootstrap Datepicker return colour for select dates - css

Ok,
so I'm using this calendar https://bootstrap-datepicker.readthedocs.io/en/latest/
I have an MVC controller which is already passing an array of dates and a known state for these dates, I can disable these fine.
What I'm trying to attempt is that for a certain state, I change the colour of the number on the calendar.
An exmaple on the site has a a rather intersting return green, now I couldn't get it work when I experimented.
So I copied the entire example(which is the code snippet), and it all worked except for the return green, yet if you us the sandbox and enable the 'before show day' you can see this returning green.
Looking at the DOM in the Sandbox you can see the class change to 'green day' in my code it changes it to 'day green'.
My question is, has anyone actually got this working?
If so, what colours can you change to? I've searched through the libary, but I'm coming up blank on how this actually works.
$('#sandbox-container div').datepicker({
beforeShowDay: function(date){
if (date.getMonth() == (new Date()).getMonth())
switch (date.getDate()){
case 4:
return {
tooltip: 'Example tooltip',
classes: 'active'
};
case 8:
return false;
**case 12:
return "green";**
}
}
});

Ok, so I actuallly worked this out while I was typing this.
add to the bootstrapper-datepicker css the below
.day.purple {
color: purple;
}
The code names the day whatever you return, so you don't need to return a color, you could return 'sausage' and on the css return green, what's important is the name you return is the name of your css class
$('#sandbox-container div').datepicker({
beforeShowDay: function(date){
if (date.getMonth() == (new Date()).getMonth())
switch (date.getDate()){
case 4:
return {
tooltip: 'Example tooltip',
classes: 'active'
};
case 8:
return false;
**case 12:
return "purple";**
}
}
});

Related

Make flatpickr input required

I'm using the amazing flatpickr on a project and need the calendar date to be mandatory.
I'm trying to have all the validation in native HTML, so I was naively trying with just adding the required attribute to the input tag, but that doesn't appear to be working.
Is there a way of natively making a date mandatory with flatpickr or do I need to write some custom checks?
You can easily achieve this by:
Passing allowInput:true in flatpickr config.
As example:
flatpickrConfig = {
allowInput: true, // prevent "readonly" prop
};
From the documentation:
Allows the user to enter a date directly into the input field. By
default, direct entry is disabled.
The downside of this solution is that you should enable the direct entry (but ideally form validation should occur whether or not direct entry is enabled).
But if you don't want to enable the direct entry to solve this problem, you can use the code below as a workaround:
flatpickrConfig = {
allowInput:true,
onOpen: function(selectedDates, dateStr, instance) {
$(instance.altInput).prop('readonly', true);
},
onClose: function(selectedDates, dateStr, instance) {
$(instance.altInput).prop('readonly', false);
$(instance.altInput).blur();
}
};
This code remove the readonly property when it is not in focus so that html validation can occur and add back the readonly prop when it is in focus to prevent manual input. More details about it here.
This is what I came up with to make as complete of a solution as possible. It prevents form submission (when no date selected and input is required), ensures browser native "field required" message pops up and prevents the user typing in the value directly.
flatpickrConfig = {
allowInput: true, // prevent "readonly" prop
onReady: function(selectedDates, dateStr, instance) {
let el = instance.element;
function preventInput(event) {
event.preventDefault();
return false;
};
el.onkeypress = el.onkeydown = el.onkeyup = preventInput; // disable key events
el.onpaste = preventInput; // disable pasting using mouse context menu
el.style.caretColor = 'transparent'; // hide blinking cursor
el.style.cursor = 'pointer'; // override cursor hover type text
el.style.color = '#585858'; // prevent text color change on focus
el.style.backgroundColor = '#f7f7f7'; // prevent bg color change on focus
},
};
There is one disadvantage to this: Keyboard shortcuts are disabled when the flatpickr is open (when the input has focus). This includes F5, Ctrl + r, Ctrl + v, etc. but excludes Ctrl + w in Chromium 88 on Linux for some reason. I developed this using a rather old flatpickr version 3.1.5, but I think it should work on more recent ones too.
In case you want to use altFormat (display one date format to user, send other date format to server), which also implies setting altInput: true, you have to also change the onReady function to use instance.altInput instead of instance.element.
The onReady event listener can probably be attached to the instance after initializing it. However, my intention of using flatpickr with vue-flatpickr-component where you cannot elegantly access the individual flatpickr instances, made me use the config field instead.
I haven't tested it on mobile devices.
After digging a bit into the GitHub repo, I found a closed issue that points out that the issue will not be addressed.
In the same Issue page there is a workaround that seems to do the trick:
$('.flatpickr-input:visible').on('focus', function () {
$(this).blur()
})
$('.flatpickr-input:visible').prop('readonly', false)
copy attr name from prior input type hidden to rendered flatpickr input
just do this
$('[name=date_open]').next('input').attr("name","date_open");
$('[name=date_close]').next('input').attr("name","date_close");
Have been working on this for a couple of days now, finally getting the result I was after.
NOTE: I am using flatpickr with jQuery validation
As you would know flatpickr uses an alternative field for the date input, the actual field where the date is stored is hidden, and this is the key.
jQuery validation has a set of defaults, and by default hidden fields are not subject to validation, which normally makes perfect sense. So we just have to turn on the validation of hidden fields to make this work.
$.validator.setDefaults({
ignore: []
});
So my validator rules are then fairly normal:
var valid = {
rules: { dateyearlevel: {required: true} },
messages: { dateyearlevel: {required: "The date is required"} }
};
$("#myform").validate(valid);
That should allow you to ensure the date is required.
In my situation I wanted my date to only be required is a checkbox was checked. To do this we changed the rule above:
var valid = {
rules: { dateyearlevel: {
required: function() { return $("#mycheckbox").is(":checked") }
} },
messages: { dateyearlevel: {required: "The date is required"} }
};
$("#myform").validate(valid);
In case this helps someone, I'm using parsley.js for frontend validation and it works good with flatpickr
enter image description here
Just to expand a bit more on this, I found the ignore value set as an empty array did the trick for me also. You can just add this to your validate call back. Also displaying was a bit of an issue so I updated the errorPlacement to allow for flatpickr inputs like so.
$('#my-form').validate({
errorPlacement: function (error, element) {
if (element.hasClass('js-flatpickr') && element.next('.js-flatpickr').length) {
error.insertAfter(element.next('.js-flatpickr'));
} else if (element.parent('.input-group').length) {
error.insertAfter(element.parent());
} else {
error.insertAfter(element);
}
},
ignore: [],
rules: {
'startdate': { required: true }
},
messages: {
'startdate': {required: "Start Date is required"}
},
submitHandler: function(form) {
// ajax form post
}
});
in my case vue ( dunno why ) , i would like to comment for comment by #mik13ST
fyi: the default allowInput i think is true, no need to define, i didnt set the properties and my flat-pickr also work on testing.
i use
// this work in flat-pickr || #code_01
<small class="text-danger">
{{ validationContext.errors[0] }}
</small>
instead of
// work for all element except <flat-pickr #code_02 , dunno why not work
<b-form-invalid-feedback>
{{ validationContext.errors[0] }}
</b-form-invalid-feedback>
full code
<validation-provider
#default="validationContext"
name="Waktu Selesai Berkegiatan *"
vid="Waktu Selesai Berkegiatan *"
rules="required"
>
<flat-pickr
id="Waktu Selesai Berkegiatan *"
v-model="item.pip_time_end_rl"
placeholder="Waktu Selesai Berkegiatan *"
class="form-control"
static="true"
:config="dpconfig"
:state="getValidationState(validationContext)"
/>
// put here the message of error ( required ) #code_01 instead of #code_02
</validation-provider>
if younot use composite,
just use
#default="{ errors }" // in validation provider
:state="errors.length > 0 ? false : null" // in element for example flat-pickr
{{ errors[0] }} // to print out the message

Fullcalendar restrict view to today + x months

I am using the fullcalendar library. How can i restrict my months view to only see the next x number months?
I dont see any straight forward answers to this in the documentation. I am not sure if I am supposed to try and alter the render methods?
Thanks
This should do the trick for you
$('#calendar').fullCalendar({
viewDisplay: function(view) {
// maybe return false aborts action?
if (view.start > lastDayOfNextMonth) {
return false;
}
// or disable next button if this is last valid month
if (view.end + oneDay >= lastValidDate) {
$("#calendar #fc-button-next").attr("disabled","disabled");
}
// or gotoDate if view.start is out of range
if (view.start > lastValidDate) {
// proceed
}
}
});
This question has a bunch of samples: FullCalendar examples

How to set editable as true only for certain users in Fullcalendar

I am using Fullcalendar for my project and I was wondering how it is possible to set event editable only for selected users.
I have tried doing this but it didn't seem to work
editable: function (event) {
if (event.createdby == "Admin") {
return true
}
else {
return false
}
},
The editable option determines if the events can be dragged and resized. Enables/disables both at the same time.
I am not sure about the event.createdby call returns something like "Admin"(or any other user).
First you please check it by print it on console.log() or simply alert(event.createdby);. If this can show you Admin somehow, then it is all about the error in your code(like missing semicolon(;) after return true and return false in your code.
If you can take the name(or even id) of the 'selected user' to a variable like createdby, then it is just eazy as it is in the code below:
Change the code:
editable: function (event) {
if (event.createdby == "Admin") {
return true
}
else {
return false
}
},
To this:
editable: (createdby == "Admin") ? true:false,
OR
editable: (createdid == 1) ? true:false,
Please note that createdby and createdid are javascript variables than contains selected user's name/id in your caledar.js file (as how you handle it in your project).
It is nothing about whether you use ASP, PHP, or MVC #... look how you can take uique users in the calendar.js file. There is a simple(best) way if you have the id in a hidden item in the content page.
That is by loading the value of the hidden field to the js variable like,
var createdid = $( "#idfield" ).val();
OR
var createdid = $( ".idfield" ).val();
Thank you.

How to cancel old selection in fullCalendar?

I use jQuery fullCalendar (http://arshaw.com/fullcalendar/docs/selection/unselectAuto/)
I use Selectable version of this calendar (http://arshaw.com/js/fullcalendar/demos/selectable.html)
It's working fine however I want to cancel/delete my old selections if I continue selecting new dates.
Lets say I chose 1 Jan and gave a title to it.
When I try to select 2 Jan, I want to see only 2 Jan selection.
I thought unselectAuto is for this but I couldnt manage to make it work :(
Any ideas?
I used unselectAuto right under
selectable: true,
unselectAuto: true,
First it's still necessary to use the $('#yourCalendar').fullCalendar('unselect'); function.
The second thing that I needed to do, was to specify how the unselect callback was going to behave (when setting up the fullcalendar options). For me I had to unbind the submit button from my form
unselect: function(){
$('#submitButton').unbind();
},
It worked great!
I was able to reach this conclusion after reading this post "multiple events created"
u can try this way, this works for me :)
var liveDate = new Date(); // current Date
var calendar = $('#calendar').fullCalendar({
select: function (startDate, endDate) {
if (liveDate > startDate) {
alert('Selected date has been passed');
return false;
} else {
//do your wish
}
calendar.fullCalendar('unselect');
}
});
Had the same problem but my user was interfacing directly with the calendar and multiple events were being generated. ie. not through a form with a button and therefore nothing to "unbind" as many of the previous solutions.
To only allow one selection and to clear previous submissions I changed the select function as follows:
select: function(start, end) {
var title = "Desired Booking";
var eventData;
eventData = {
title: title,
start: start,
end: end
};
$('#calendar').fullCalendar('renderEvent', eventData, true); },
select: function(start, end) {
$('#calendar').fullCalendar('removeEvents');
$('#calendar').fullCalendar('rerenderEvents')
var title = "Desired Booking";
var eventData;
eventData = {
title: title,
start: start,
end: end
};
$('#calendar').fullCalendar('renderEvent', eventData, true); },
This did the trick for me.
I had problems with unselectAuto also. Sometimes it would unselect when I didn't want it to, and sometimes it would NOT unselect when I DID want it to. My solution was to manually trigger the unselect method.
Here's how to unselect all currently selected:
$('#yourCalendar').fullCalendar('unselect');
You can put this line of code inside custom jQuery events that you bind outside of the plugin. You can also include it in fullCalendar callbacks, etc...
Hope this helps.
Scott
Here is an exemple of Version 5 doing the unselect
You could do it by :
const calendarApi = selectInfo.view.calendar;
calendarApi.unselect(); // clear date selection
Use this code
$('#trainings_modal').on('hidden', function () {
$('#trainings_modal *').unbind(); // Unbind all events
});
Unbind on hide form with any method (i.e esc press, or out key)

How to add a row hyperlink for an extJS Grid?

Can someone please throw some light on how to go about rendering an hyperlink in the cells of a particular column in ExtJS?
I have tried binding the column to a render function in my JS, from which I send back the html:
SELECT
However, with this, the problem is that, once I hit the controller through the link, the navigation is successful, but subsequent navigations to the data-grid show up only empty records.
The records get fetched from the DB successfully through the Spring MVC controller, I have checked.
Please note that this happens only once I use the row hyperlink in the extJS grid to navigate away from the grid. If I come to the grid, and navigate elsewhere and again come back to the grid, the data is displayed fine.
The problem only occurs in case of navigating away from the grid, using the hyperlink rendered in one/any of the cells.
Thanks for your help!
This is for ExtJS 4 and 5.
Use a renderer to make the contents look like a link:
renderer: function (value) {
return ''+value+'';
}
Then use the undocumented, dynamically generated View event cellclick to process the click:
viewConfig: {
listeners: {
cellclick: function (view, cell, cellIndex, record, row, rowIndex, e) {
var linkClicked = (e.target.tagName == 'A');
var clickedDataIndex =
view.panel.headerCt.getHeaderAtIndex(cellIndex).dataIndex;
if (linkClicked && clickedDataIndex == '...') {
alert(record.get('id'));
}
}
}
}
Try something like this:
Ext.define('Names', {
extend: 'Ext.data.Model',
fields: [
{ type: 'string', name: 'Id' },
{ type: 'string', name: 'Link' },
{ type: 'string', name: 'Name' }
]
});
var grid = Ext.create('Ext.grid.Panel', {
store: store,
columns: [
{
text: 'Id',
dataIndex: 'Id'
},
{
text: 'Name',
dataIndex: 'Name',
renderer: function (val, meta, record) {
return '' + val + '';
}
}
...
...
...
However my thanks to - ExtJS Data Grid Column renderer to have multiple values
Instead of using an anchor tag, I would probably use plain cell content styled to look like an anchor (using basic CSS) and handle the cellclick event of the GridPanel to handle the action. This avoids dealing with the anchor's default click behavior reloading the page (which is what I'm assuming is happening).
I created a renderer so it looked like you were clicking on it.
aRenderer: function (val, metaData, record, rowIndex, colIndex, store){
// Using CellClick to invoke
return "<a>View</a>";
},
But I used a cell event to manage the click.
cellclick: {
fn: function (o, idx, column, e) {
if (column == 1) // Doesn't prevent the user from moving the column
{
var store = o.getStore();
var record = store.getAt(idx);
// Do work
}
}
}
For these purposes I use CellActions or RowActions plugin depending on what I actually need and handle cell click through it.
If you want something that looks like an anchor, use <span> instead and do what #bmoeskau suggested.
You can use 'renderer' function to include any HTML you want into cell.
Thanks guys for your response.
AFter debugging the extJS-all.js script, I found the issue to be on the server side.
In my Spring MVC controller, I was setting the model to the session, which in the use-case I mentioned earlier, used to reset the "totalProperty" of Ext.data.XmlStore to 0, and hence subsequent hits to the grid, used to display empty records.
This is because, ext-JS grid, checks the "totalProperty" value, before it even iterates through the records from the dataStore. In my case, the dataStore had data, but the size was reset to null, and hence the issue showed up.
Thanks to all again for your inputs!

Resources