How can we do date highlight which we particular disabled using jquery in ui datepicker - jquery-ui

Here is my code as below, Please help me to find out solution for add highlight on those dates which I particularly disabled and Sundays.
And Do not want to highlight disabled previous dates from current date.
In this how can add highlights on particular dates which I disabled.
$(document).ready(function(){
jQuery(function() {
var blockedDates = ["12/20/2022", "12/28/2022", "12/24/2022", "12/19/2022"];
var dateFormat = "yy-mm-dd";
$( "#datepicker" ).datepicker({
dateFormat:'yy-mm-dd',
minDate: 0,
daysOfWeekDisabled: [0, 6],
onSelect: function(dateStr) {
var _frmdate = $.trim($(this).val());
jQuery("#blockModalDateItem").modal("show");
jQuery("#bk_blockdt").val(_frmdate);
jQuery(".status_msg").html("");
},
beforeShowDay: function(date){
show = true;
if(date.getDay() == 0 ){show = false;}
for (var i = 0; i < blockedDates.length; i++) {
if (new Date(blockedDates[i]).toString() == date.toString()) {show = false;}
}
var display = [show,'',(show)?'':'Block Settlement Date']; //Disabled Particular dates & all Sundays.
return display;
}
});
});

You can use CSS to apply styles to disabled dates. Specifically targeting dates with title="Block Settlement Date"
.ui-datepicker-unselectable.ui-state-disabled[title="Block Settlement Date"] {
background:red;
}

Thank you to all, For giving precious time to help my queries.
But I found my custom solution for my problem & I would like to share here may this will help to others.
New changes added to datepicker in beforeshowday is here, in this i have added custom class.
$(document).ready(function(){
jQuery(function() {
var blockedDates = ["12/20/2022", "12/28/2022", "12/24/2022", "12/19/2022"];
var dateFormat = "yy-mm-dd";
$( "#datepicker" ).datepicker({
dateFormat:'yy-mm-dd',
minDate: 0,
daysOfWeekDisabled: [0, 6],
onSelect: function(dateStr) {
var _frmdate = $.trim($(this).val());
jQuery("#blockModalDateItem").modal("show");
jQuery("#bk_blockdt").val(_frmdate);
jQuery(".status_msg").html("");
},
beforeShowDay: function(date){
show = true;
if(date.getDay() == 0 ){show = false;}
for (var i = 0; i < blockedDates.length; i++) {
if (new Date(blockedDates[i]).toString() == date.toString()) {show = false;}
}
var display = [show,'highlight-bkdate',(show)?'':'Block Settlement Date']; //Disabled Particular dates & all Sundays.
return display;
}
});
});
In this class i have applied some css for giving highlight purpose.
.highlight-bkdate span {
color: #fff!important;
background-color: red!important;
border: 3px solid #191970!important;
}
Now this state it will highlight all disabled dates, Now I want to only particular dates & sunday should highlight.
So, I called this function after datepicker load. In this I again removed class on those dates which I do not want to highlight.
setTimeout(removeClassHigh, 50);
function removeClassHigh(){
var blockedDates = ["12/20/2022", "12/28/2022", "12/24/2022", "12/19/2022"];
var dayNames = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'];
var currentYear = jQuery(".ui-datepicker-year").text();
var currentMonth = jQuery(".ui-datepicker-month").text();
var oneMonth = 1;
var dat = new Date('1 ' + currentMonth +' ' +currentYear);
var monthNo = dat.getMonth();
oneMonth += Number(monthNo);
var f1 = 1;
var d = new Date();
var day = d.getDate();
$('.ui-state-default').each(function () {
var checkCurrentDt = new Date(oneMonth+'/'+f1+'/'+currentYear);
var checkThisDay = checkCurrentDt.getDay();
var checkThisDate = String(checkCurrentDt.getDate()).padStart(2, '0');
if(day==f1){
return false;
}else{
if(dayNames[checkThisDay]!="Sunday"){
if (jQuery.inArray(oneMonth+'/'+checkThisDate+'/'+currentYear, blockedDates) === -1) {
$(this).parent().removeClass('highlight-bkdate');
}
}
}
f1++;
});
}
So in this way found this solution.
And Result as below:
Thank you to all..!!
Have a great day :)

Related

Google Calendar Orderby when using two linq queries

I am using google charts to display a stacked column chart. I am using entity framework and linq queries to gather my data from the db.
The problems I am having is:
that it will not order the chart. I have ordered the chart but the x-axis remains un-ordered. Can this be done through the linq query or could I do it in the script?
Currently it only displays x-axis values for data that I have. Example is on the x-axis I have month number but it only displays marks for data I have eg. 1,4,5,6. Is there a way to include from 1-12 although there is no data for that particular month number?
Code:
#region Total Hours Per Month sick
var querythpshols = (from r in db.HolidayRequestForms
where (r.StartDate) >= dateAndTime
group r by r.MonthOfHoliday into g
select new { Value = g.Key, Count = g.Sum(h => h.HoursTaken)});
var resultthpshols = querythpshols.ToList();
var datachartthpshols = new object[resultthpshols.Count];
int G = 0;
foreach (var i in resultthpshols)
{
datachartthpshols[G] = new object[] { i.Value.ToString(), i.Count };
G++;
}
string datathpshols = JsonConvert.SerializeObject(datachartthpshols, Formatting.None);
ViewBag.datajthpshols = new HtmlString(datathpshols);
#endregion
#region Total Hours Per Month
var querythpshols1 = (from r in db.HolidayRequestForms
where (r.StartDate) <= dateAndTime
group r by r.MonthOfHoliday into g
select new { Value = g.Key, Count1 = g.Sum(r => r.HoursTaken) })
;
var resultthpshols1 = querythpshols1.ToList();
var datachartthpshols1 = new object[resultthpshols1.Count];
int P = 0;
foreach (var i in resultthpshols1)
{
datachartthpshols1[P] = new object[] { i.Value.ToString(), i.Count1 };
P++;
}
string datathpshols1 = JsonConvert.SerializeObject(datachartthpshols1, Formatting.None);
ViewBag.datajthpshols1 = new HtmlString(datathpshols1);
#endregion
Script:
#*TOTAL HOURS PER MONTH CHART*#
<scipt>
<script>
var datathpshols = '#ViewBag.datajthpshols';
var datassthpshols = JSON.parse(datathpshols);
var datathpshols1 = '#ViewBag.datajthpshols1';
var datassthpshols1 = JSON.parse(datathpshols1);
</script>
<script type="text/javascript">
// Load the Visualization API and the corechart package.
google.charts.load('current', { 'packages': ['corechart'] });
// Set a callback to run when the Google Visualization API is loaded.
google.charts.setOnLoadCallback(drawChartA);
// Callback that creates and populates a data table,
// instantiates the pie chart, passes in the data and
// draws it.
function drawChartA() {
// Create the data table.
var data1 = new google.visualization.DataTable();
data1.addColumn('string', 'Value');
data1.addColumn('number', 'Holiday Hours Booked');
data1.addRows(datassthpshols);
var data2 = new google.visualization.DataTable();
data2.addColumn('string', 'Value');
data2.addColumn('number', 'Holiday Hours Taken');
data2.addRows(datassthpshols1);
var joinedData = google.visualization.data.join(data1, data2, 'full', [[0, 0]], [1], [1]);
// Set chart options
var options = {
'title': 'Holiday Hours Taken Per Month',
'width': 600,
'height': 350,
'hAxis': { title: 'Month Number' },
'vAxis': { title: 'Holiday Hours Taken' },
'is3D': true,
'isStacked': true,
'legend': 'right'
};
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.ColumnChart(document.getElementById('chartTHPShols_div'));
chart.draw(joinedData, options);
}
</script>
1) Use data table method --> sort -- to order the x-axis.
joinedData.sort([{column: 0}]);
2) strings produce a discrete axis, and will only display the data available. numbers produce a continuous axis, and provide much more flexibility for the axis ticks. probably the most simplest solution would be to use a data view to convert the x-axis to numbers. (use the data view to draw the chart)
var joinedData = google.visualization.data.join(data1, data2, 'full', [[0, 0]], [1], [1]);
var dataView = new google.visualization.DataView(joinedData);
dataView.setColumns([{
calc: function (dt, row) {
return parseFloat(dt.getValue(row, 0));
},
label: joinedData.getColumnLabel(0),
type: 'number'
}, 1, 2]);
chart.draw(dataView, options);

Appending string for value to jQuery.ui handle

So close! Why on earth is this code not working? On the first slide it gets it's new value (2) but keeps the same message "terrible". Then after that works fine, except the messages are all stepped back one position. It's driving me mad!
var messages = {
1: "terrible",
2: "okay",
3: "better",
4: "great",
5: "super!"
};
initialValue = 1
var messageUpdate = function(event, ui) {
var curValue = ui.value || initialValue;
var message = '<div id="out">' + (messages[$('#slider').slider('value')]) + '</div>';
$('.ui-slider-handle').html(message);
}
$("#slider").slider({
value: initialValue,
min: 1,
max: 5,
step: 1,
create: messageUpdate,
slide: messageUpdate
});
Of course, as soon as you see it on here in black and white it becomes obvious:
var curValue = ui.value || initialValue;
var message = '<div id="out">' + (messages[curValue]) + '</div>';
I was not using my own code!

Trigger cocoon add_association from javascript

I am using cocoon and I want to automatically add a child record when a date(can be multiple dates) in a date picker is selected.
I can trap the date selections in coffeescript like this, but I don't know how to get a child record added through cocoon i.e. by emulating what happens when the link_to_add_association is fired.
$(".form_multidate").datepicker().on 'changeDate', (e) -> alert(e.dates)
the cocoon setup is a standard nested form, no tricks, working fine on the page.
EDIT: Code mentioned in comment re binding calendar:
$(document).ready(function() {
$('#other_request_details')
.bind('cocoon:after-insert', function() {
return $('.datepicker-single').datepicker({
dateFormat: "DD, dd M yy"
});
});
});
Calling a JS function in order to add a new record with Cocoon is not possible. The only thing you can do is trigger the click event of the add association button.
If you see Cocoon's library code you will see that all new record functionality is bound to the click button
$(document).on('click', '.add_fields', function(e) {
e.preventDefault();
var $this = $(this),
assoc = $this.data('association'),
assocs = $this.data('associations'),
content = $this.data('association-insertion-template'),
insertionMethod = $this.data('association-insertion-method') || $this.data('association-insertion-position') || 'before',
insertionNode = $this.data('association-insertion-node'),
insertionTraversal = $this.data('association-insertion-traversal'),
count = parseInt($this.data('count'), 10),
regexp_braced = new RegExp('\\[new_' + assoc + '\\](.*?\\s)', 'g'),
regexp_underscord = new RegExp('_new_' + assoc + '_(\\w*)', 'g'),
new_id = create_new_id(),
new_content = content.replace(regexp_braced, newcontent_braced(new_id)),
new_contents = [];
if (new_content == content) {
regexp_braced = new RegExp('\\[new_' + assocs + '\\](.*?\\s)', 'g');
regexp_underscord = new RegExp('_new_' + assocs + '_(\\w*)', 'g');
new_content = content.replace(regexp_braced, newcontent_braced(new_id));
}
new_content = new_content.replace(regexp_underscord, newcontent_underscord(new_id));
new_contents = [new_content];
count = (isNaN(count) ? 1 : Math.max(count, 1));
count -= 1;
while (count) {
new_id = create_new_id();
new_content = content.replace(regexp_braced, newcontent_braced(new_id));
new_content = new_content.replace(regexp_underscord, newcontent_underscord(new_id));
new_contents.push(new_content);
count -= 1;
}
var insertionNodeElem = getInsertionNodeElem(insertionNode, insertionTraversal, $this)
if( !insertionNodeElem || (insertionNodeElem.length == 0) ){
console.warn("Couldn't find the element to insert the template. Make sure your `data-association-insertion-*` on `link_to_add_association` is correct.")
}
$.each(new_contents, function(i, node) {
var contentNode = $(node);
insertionNodeElem.trigger('cocoon:before-insert', [contentNode]);
// allow any of the jquery dom manipulation methods (after, before, append, prepend, etc)
// to be called on the node. allows the insertion node to be the parent of the inserted
// code and doesn't force it to be a sibling like after/before does. default: 'before'
var addedContent = insertionNodeElem[insertionMethod](contentNode);
insertionNodeElem.trigger('cocoon:after-insert', [contentNode]);
});
});

jquery ui - disable today and highlight next 3 days

So far I can disable Today's date, but I'm coming up short trying to highlight the next 3 days
$( "#someDiv" ).datepicker({
beforeShowDay: function( date ){
//disable Sundays;
return [date.getDay() != 0, '']
},
/* today is disabled */
minDate: 1
});
... or is there a way to render individual day cells with date info as data attributes or something like that?
In your return, add a condition that will check for the date range you want and add a class to those dates.
Here is a jsFiddle with the full example. I'm sure this can be improved upon though.
The code and CSS to add a background to the dates when the condition is true (style it how you like):
.highlightDay .ui-state-default {
background: #484;
color: #FFF;
}
$(document).ready(function() {
$("#datepicker").datepicker({
beforeShowDay: function(date) {
var newDate = addDays(new Date(), 0);
var thirdDay = addDays(new Date(), 3);
return [date.getDay() != 6,
// This can probably be improved
date >= newDate && date <= thirdDay ? "highlightDay" : ""];
},
minDate: 1
});
});
function addDays(theDate, days) {
return new Date(theDate.getTime() + days*24*60*60*1000);
}

jQuery UI Datepicker - Disable specific days selected from database not from arrays

Thanks in advance for your cooperation,
I'm using this JQUERY Date picker as shown in this image :
http://techblog.willshouse.com/wp-content/uploads/2009/06/datepicker.jpg
and for more information :
I have an ASP.net site retrieving data from SQL server 2008..
one of the admin functionalities is to change official holidays dates and save them in the DB in table Holidays
my question is:
how to disable these official holidays in the datepicker , so i prevent the user to select these specific days.
following this link:
jQuery UI Datepicker - Disable specific days
but I’m afraid I can’t use this solution manner , because the official holidays can’t be listed in an array since they are changed periodically many times by the admin of the site.
So, I don’t need to add them to the array list every time the admin change them.
I mean, is there any way to disable the selected dates from the table "Holidays" in the database?
Thanks in advance,
--- and also , i try to use this answer...
/* create an array of days which need to be disabled */
var disabledDays = ["2-21-2010","2-24-2010","2-27-2010","2-28-2010","3-3-2010","3-17-2010","4-2-2010","4-3-2010","4-4-2010","4-5-2010"];
/* utility functions */
function nationalDays(date) {
var m = date.getMonth(), d = date.getDate(), y = date.getFullYear();
//console.log('Checking (raw): ' + m + '-' + d + '-' + y);
for (i = 0; i < disabledDays.length; i++) {
if($.inArray((m+1) + '-' + d + '-' + y,disabledDays) != -1 || new Date() > date) {
//console.log('bad: ' + (m+1) + '-' + d + '-' + y + ' / ' + disabledDays[i]);
return [false];
}
}
//console.log('good: ' + (m+1) + '-' + d + '-' + y);
return [true];
}
function noWeekendsOrHolidays(date) {
var noWeekend = jQuery.datepicker.noWeekends(date);
return noWeekend[0] ? nationalDays(date) : noWeekend;
}
/* create datepicker */
jQuery(document).ready(function() {
jQuery('#date').datepicker({
minDate: new Date(2010, 0, 1),
maxDate: new Date(2010, 5, 31),
dateFormat: 'DD, MM, d, yy',
constrainInput: true,
beforeShowDay: noWeekendsOrHolidays
});
Here is a way to disable specific dates from being selected:
jQuery - Datepicker - Disable Specific Dates
Looking at the array in this link, instead of:
var unavailableDates = ["9-5-2011","14-5-2011","15-5-2011"];
You would have something like:
<?php
$result = mysql_query("SELECT `date` FROM `Holidays`;")
foreach ($result as $holiday){
//may need to format $holiday here before using
$dates .= "'".$holiday."',";
}
//remove the last comma
$dates = substr($dates,0,-1);
?>
var unavailableDates = [<?php echo $dates; ?>];
Perhaps someone else can provide an ASP.NET solution?
For anyone's interest, here is how I did it with ColdFusion
<cfquery name="qHolidays" datasource="#ds#">
SELECT holiday_date
FROM public_hols
ORDER BY holiday_date
</cfquery>
<cfset disabledDays = '"1-1-2000"'>
<cfloop query="qHolidays">
<cfset disabledDays = disabledDays & ',"' & DateFormat(holiday_date,'d-m-yyyy') & '"'>
</cfloop>
<cfoutput>
<script type="text/javascript">
/* create an array of days which need to be disabled */
var unavailableDates = [#disabledDays#];
//var unavailableDates = ["9-5-2011","14-5-2011","15-5-2011"];
function unavailable(date) {
dmy = date.getDate() + "-" + (date.getMonth()+1) + "-" + date.getFullYear();
day = date.getDay();
if ( $.inArray(dmy, unavailableDates) < 0 && (day > 0) && (day < 7) ) {
return [true,"","Work Day"];
} else {
return [false,"","Public Holiday"];
}
}
/*
$('##iDate').datepicker({ beforeShowDay: unavailable });
*/
jQuery(document).ready(function() {
$(function() {
$('##dateentered').datepicker({
changeMonth: true,
changeYear: true,
dateFormat: 'yy-mm-dd',
showOn: "button",
buttonImage: "images/calendar.gif",
buttonImageOnly: true,
numberOfMonths: 3,
constrainInput: true,
beforeShowDay: unavailable
});
});
});
</script>
</cfoutput>

Resources