How to add one and more leaves in jquery datepicker - javascript

I add leave in datepicker using array but, two leave is on same day is not showing in calendar only first leave in array is showing but second leave is not showing.
my var leaveday array is like this = "2021,09,28,Love is on Leave-2021,09,18,Pravin is on Leave-2021,09,25,Darshit is on Leave-2021,09,18,Love is on Leave-"
my jquery is here
var leave_dates= $("#all_past_leave").val();
if(leave_dates !== null && leave_dates !== '' && leave_dates !== undefined) {
var leave_all = leave_dates.slice(0,-1);
var leaveDays = leave_all.split('-');
}
$(function() {
$("#past_leave").datepicker({
numberOfMonths:3,
beforeShowDay: setLeaveDays
});
// set Leave function which is configured in beforeShowDay
function setLeaveDays(date) {
for (i = 0; i < leaveDays.length; i++) {
var leaveData = leaveDays[i].split(',');
if (date.getFullYear() == leaveData[0]
&& date.getMonth() == leaveData[1] - 1
&& date.getDate() == leaveData[2]) {
return [true, 'staff_leaves', leaveData[3]];
}
}
return [true, ''];
}
});
I am getting result like this see image here
but I want result like this I edited from chrome inspect for example see image here

Related

Reset a list after a reset of the dropdown selection

I have made a list. I've added some dropdown to sort the list. Once its sorted, I would like to be able to reset the dropdown back to nothing. (Accomplished that already). But the list doesn't update back to as if nothing was selected. How can I do that?
Code im using to manipulate the list:
<script>
$.noConflict();
jQuery( document ).ready(function( $ ) {
$('.container').on("change", 'select', function() {
var type = $('#BBFHtype').val().toLowerCase(),
surface = $('#BBFHsurface').val().toLowerCase(),
sticking = $('#BBFHsticking').val().toLowerCase(),
panel = $('#BBFHpanel').val().toLowerCase(),
height = $('#BBFHheight').val().toLowerCase(),
thickness = $('#BBFHthickness').val().toLowerCase();
var table = $("#BBFHDoors");
var trs = table.find('tr');
trs.hide();
var filtered = trs.filter(function(index, elem) {
var tds = $(elem).find('td');
if (type !== "all" && tds.eq(1).text().trim().toLowerCase() !== type) {return false;}
if (surface !== "all" && tds.eq(2).text().trim().toLowerCase() !== surface) {return false;}
if (sticking !== "all" && tds.eq(3).text().trim().toLowerCase() !== sticking) {return false;}
if (panel !== "all" && tds.eq(4).text().trim().toLowerCase() !== panel) {return false;}
if (height !== "all" && tds.eq(5).text().trim().toLowerCase() !== height) {return false;}
if (thickness !== "all" && tds.eq(6).text().trim().toLowerCase() !== thickness) {return false;}
return true;
})
filtered.show();
if (filtered.length == 0) {
alert("No Records Found!!!");
}
});
});
</script>
Code im using to reset the selections back to nothing:
$(function () {$("#btnReset").bind("click", function ()
{$("#BBFHtype")[0].selectedIndex = 0;
$("#BBFHsurface")[0].selectedIndex = 0;
$("#BBFHsticking")[0].selectedIndex = 0;
$("#BBFHpanel")[0].selectedIndex = 0;
$("#BBFHheight")[0].selectedIndex = 0;
$("#BBFHthickness")[0].selectedIndex = 0;
});});
Ive tried playing around with .prop and .attr(selected), and removeattr(). But haven't been successful. EX: $("#BBFHtype")[0].prop("selected", true);
Any help would be awesome!
Just trigger change on the select elements:
$('select').trigger('change');
Complete function:
$(function () {$("#btnReset").bind("click", function ()
{$("#BBFHtype")[0].selectedIndex = 0;
$("#BBFHsurface")[0].selectedIndex = 0;
$("#BBFHsticking")[0].selectedIndex = 0;
$("#BBFHpanel")[0].selectedIndex = 0;
$("#BBFHheight")[0].selectedIndex = 0;
$("#BBFHthickness")[0].selectedIndex = 0;
$('select').trigger('change');
});});
Also, see complete working demo here

.each function () for cloned inputs

Trying to create the Preview form and do not understand why each function () not working in this script. Or works but only for the last cloned row and ignore the zero values ​​in the previously cloned inputs.
$('input[id^=Mult_factor_]').each(function () {
var MultFactor = $(this).val();
var TotPoints = $('#Tot_points').val();
var exp1 = "Overload";
var exp2 = "Load is: ";
if (MultFactor < 1 || TotPoints > 100) {
$('#ExemptionLimitsText').text(exp1).show();
$('#PrwTotPointsText').hide();
} else {
$('#ExemptionLimitsText').text(exp2).show();
$('#PrwTotPointsText').text($('#Tot_points').val()).show();
}
});
JSfiddle
I need: If at least one of cloned MultiFactor value is zero show "Overload"
Based on your comment, you want to display the word "Overload" if either the "Additional" field is over 100 or if any of the multifactor fields is 0.
However, your loop continues to process if either of these conditions are met.
Do not use a loop, instead search specifically for a multifaktor value of 0.
var totalPoints = parseInt($('#Tot_points').val());
if(totalPoints > 100 || $('input[name="MultFaktor"]').filter(function(){return this.value=='0'}).length > 0) {
$('#ExemptionLimitsText').text("Overload").show();
$('#PrwTotPointsText').hide();
} else {
$('#ExemptionLimitsText').text("Load is: ").show();
$('#PrwTotPointsText').text(totalPoints).show();
}
Return false on overload
var valid = true;
var exp1 = "Overload";
var exp2 = "Load is: ";
var TotPoints = $('#Tot_points').val();
$('input[name=MultFaktor]').each(function () {
var $this = $(this);
if ($.trim($(this).val()) == '0' || TotPoints > 100) {
valid = false;
} else {
$('#ExemptionLimitsText').text(exp2).show();
$('#PrwTotPointsText').text($('#Tot_points').val()).show();
}
});
if (valid == false) {
e.preventDefault();
$('#ExemptionLimitsText').text(exp1).show();
$('#PrwTotPointsText').hide();
}

My DataTables date range filter using jQuery UI Datepicker works only in Google Chrome

I feel like I could use another pair of eyes on my code right now.
I am using jQuery UI's Datepicker to grab dates from two html inputs:
<!-- HTML inputs -->
<p id="date_filter">
<span id="date-label-from" class="date-label"><?php echo LANG_FROMDATE; ?>: </span><input class="date_range_filter date" type="text" id="datepicker_min" /><img id="calender-from" class="datepicker-calender" src="includes/js/jquery/jquery-ui/img/calendar.png" width="17px" height="18px" />
<span id="date-label-to" class="date-label"><?php echo LANG_TODATE; ?>: </span><input class="date_range_filter date" type="text" id="datepicker_max" /><img id="calender-to" class="datepicker-calender" src="includes/js/jquery/jquery-ui/img/calendar.png" width="17px" height="18px" />
<button class="btn" id="reset_btn"><?php echo LANG_RESET; ?></button>
</p>
That calender img tag is just an icon that also triggers the datepicker, i.e. like this:
$(document).ready(function() {
$('#calender-from').click(function() {
$("#datepicker_min").datepicker("show");
});
$('#calender-to').click(function() {
$("#datepicker_max").datepicker("show");
});
});
So that's the basic stuff that's all good. The issue I'm having is I have written javascript that is an extension to the DataTables filtering api. I wrote my code based on this example: https://datatables.net/examples/plug-ins/range_filtering.html
The problem is right now my code is only working in Google Chrome and fails in FireFox, Safari, and Internet Explorer. I probably am just missing something small or have some minor semantic mistake in my code.
I extend the DataTables filtering API like this:
// Date range filter
var minDateFilter = "";
var maxDateFilter = "";
$.fn.dataTableExt.afnFiltering.push(
function( oSettings, aData, iDataIndex ) {
if ( typeof aData._date == 'undefined' ) {
aData._date = new Date(aData[0]).getTime();
}
if ( minDateFilter && !isNaN(minDateFilter) ) {
if ( aData._date < minDateFilter ) {
return false;
}
}
if ( maxDateFilter && !isNaN(maxDateFilter) ) {
if ( aData._date > maxDateFilter ) {
return false;
}
}
return true;
}
);
This way seems to return false in other browsers because I will get a result of "Showing 1 - 50 of 67 records" regardless of what data I have in the datapicker inputs.
I'm handling the jQuery UI Datepicker inputs like this:
$(document).ready(function() {
$("#datepicker_min").datepicker({
"onSelect": function(date) {
minDateFilter = new Date(date).getTime();
oTable.fnDraw();
}
}).keyup(function(){
minDateFilter = new Date(this.value).getTime();
oTable.fnDraw();
});
$( "#datepicker_max" ).datepicker( {
"onSelect": function(date) {
maxDateFilter = new Date(date).getTime();
oTable.fnDraw();
}
}).keyup(function(){
maxDateFilter = new Date(this.value).getTime();
oTable.fnDraw();
});
});
I also tried extending the filter API like this (to be closer to original DataTables example):
$.fn.dataTableExt.afnFiltering.push(
function( oSettings, aData, iDataIndex ) {
var iMin = minDateFilter;
var iMax = maxDateFilter;
var iDate = new Date(aData[0]).getTime();
if ( iMin == "" && iMax == "" )
{
return true;
}
else if ( iMin == "" && iDate < iMax )
{
console.log("iDate 1 = "+iDate);
return true;
}
else if ( iMin < iDate && "" == iMax )
{
console.log("iDate 2 = "+iDate);
return true;
}
else if ( iMin < iDate && iDate < iMax )
{
console.log("iDate = 3 "+iDate);
return true;
}
return false;
}
);
When I do it this way I get a somewhat similar result of my filter code working correctly only in Chrome, and in the other browsers I'll get a result of "Showing 0 to 0 records (filtered from 67 total records)" so here it returns true but it filters incorrectly - i.e. it shows 0 results after filtering regardless of what values are in the datepicker inputs.
Ugh! why is my code only working in Google Chrome and not working in other browsers (Safari, IE, FireFox)?? Any help is appreciated, thanks in advance!
I have created a plunker from your script and added some made up html table. I used as much of your code as possible but had to adjust some of your ids.
I'm not sure where along the way i made changes that finally got this working, but I guess its mainly related to your filter variables being not global.
// Date range filter
minDateFilter = "";
maxDateFilter = "";
instead of:
// Date range filter
var minDateFilter = "";
var maxDateFilter = "";
Have a look at this Plunker with the full code which runs perfectly on FF 27.0.1 and find out for yourself.
Update:
Simplified the datepicker initialisition to this:
$("#datepicker_from").datepicker({
showOn: "button",
buttonImage: "images/calendar.gif",
buttonImageOnly: false,
"onSelect": function(date) {
minDateFilter = new Date(date).getTime();
oTable.fnDraw();
}
}).keyup(function() {
minDateFilter = new Date(this.value).getTime();
oTable.fnDraw();
});
This prevents the double assignement of the widget you have done in:
$('#calender-from').click(function() {
$("#datepicker_min").datepicker("show");
});
and:
$("#datepicker_min").datepicker({
"onSelect": function(date) {
minDateFilter = new Date(date).getTime();
oTable.fnDraw();
}
Now it uses its native function to diplay an icon.
Maybe some browser are picky about this.
Updated Plunker
Here is the script that worked for me.
$.fn.dataTableExt.afnFiltering.push(
function(oSettings, aData, iDataIndex){
var dateStart = parseDateValue($("#dateStart").val());
var dateEnd = parseDateValue($("#dateEnd").val());
var evalDate= parseDateValue(aData[5]);
var evalDate1= parseDateValue(aData[6]);
if ((evalDate >= dateStart && evalDate <= dateEnd)||(evalDate1 >= dateStart && evalDate1 <= dateEnd)) {
return true;
}
else {
return false;
}
});`
After all this time I actually finally found out what causes this issue.
Turns out it is an issue with javascript date time objects being parsed differently in different browsers.
So, in order to make your filters fully cross browser friendly, you just need to use date format in your jQuery UI datepicker that works for all broswers to parse dates from using JS new Date(date_var). But that's easier said than done. What I do is manipulate the date time value before sending it through the custom Datatables filter.
See below for the most recent cross browser implementation I've made. It's overall a better implementation than what is in my question because you don't need to worry as much about the filtering api extension it is handled automatically by the function. See the comments in the code itself for an example where I manipulate the date format to work nicely in Safari's date.parse(dateString) syntax.
$(document).ready( function () {
// define vars
var dTable = $('#transactions'),
date_from = null,
date_to = null,
dateRangeFromSearchBox = $('#date_from_range_search'),
dateRangeToSearchBox = $('#date_to_range_search'),
dateRangeResetButton = $('#date_range_reset_button');
// bootstrap our datatable
dTable.DataTable();
// bootstrap datepickers
$('input.datepicker').datepicker({
dateFormat: 'yy-mm-dd',
onSelect: function (date) {
date_from = new Date( dateRangeFromSearchBox.val() ).getTime();
date_to = new Date( dateRangeToSearchBox.val() ).getTime();
// force change event
dateRangeFromSearchBox.trigger('change');
dateRangeToSearchBox.trigger('change');
// disable further if filtering occured
if (!isNaN(date_from) &&
!isNaN(date_from) &&
dateRangeFromSearchBox.val().length > 0 &&
dateRangeToSearchBox.val().length > 0) {
dateRangeFromSearchBox.prop('disabled', true);
dateRangeToSearchBox.prop('disabled', true);
}
}
});
// date range search
// date from
dateRangeFromSearchBox.change( function () {
if (date_from === "" ||
date_to === "" ||
dateRangeFromSearchBox.val().length === 0 ||
dateRangeToSearchBox.val().length === 0) {
//console.log('reset event from box');
dTable_filterColumnByDateRange (dTable, 1, '', '');
// exit asap if date is invalid
} else if ( isNaN(date_from) || isNaN(date_to) ) {
//console.log('nan event from box')
return;
} else {
//console.log('filter event from box');
// we good? let's filter
dTable_filterColumnByDateRange (dTable, 1, date_from, date_to);
}
});
// date to
dateRangeToSearchBox.change( function () {
if (date_from === "" ||
date_to === "" ||
dateRangeFromSearchBox.val().length === 0 ||
dateRangeToSearchBox.val().length === 0) {
//console.log('reset event to box');
dTable_filterColumnByDateRange (dTable, 1, '', '');
// exit asap if date is invalid
} else if ( isNaN( new Date( dateRangeToSearchBox.val() ).getTime() ) || isNaN(date_from) ) {
//console.log('nan event to box')
return;
} else {
//console.log('filter event from box');
// we good? let's filter
dTable_filterColumnByDateRange (dTable, 1, date_from, date_to);
}
});
//date range reset
dateRangeResetButton.click( function () {
//console.log('reset event');
// this part is crazy
// don't worry I know it is
$('#date_from_range_search').val('').promise().done( function () {
$(this)
.trigger('change')
.prop('disabled', false);
$('#date_to_range_search').val('').promise().done( function () {
$(this)
.trigger('change')
.prop('disabled', false);
});
});
});
});
// and now here is our worker function
// which the above dom ready code is calling:
/**
* Filters a single column based on two date range values
* #param {Object} data_table - jQuery html object instance of the table
* #param {Integer} column_index - DataTables int value of date column to filter
* #param {Integer} date_from - unix time stamp of start date to filter between
* #param {Integer} date_to - unix time stamp of end date to filter between
*/
dTable_filterColumnByDateRange = function (data_table, column_index, date_from, date_to) {
var rowValue_asTimeStamp = null;
data_table
.DataTable()
.column()
.data()
.filter( function (value, index) {
rowValue_asTimeStamp = new Date(value).getTime();
// debug:
//console.log('from', date_from);
//console.log('to', date_to);
//console.log('row', rowValue_asTimeStamp);
//console.log('existing filters?', $.fn.dataTableExt.afnFiltering.length);
if (date_to == null ||
date_to == "" ||
date_from == null ||
date_from == "") {
$.fn.dataTableExt.afnFiltering.pop();
var returnVal = true;
} else {
var returnVal = (rowValue_asTimeStamp >= date_from && rowValue_asTimeStamp <= date_to) ? true : false;
}
})
.draw();
// extend the filter API in the
// most annoying way possible
$.fn.dataTableExt.afnFiltering.push(
function (oSettings, aData, iDataIndex) {
// built in reset?
if (date_to == null ||
date_to == "" ||
date_from == null ||
date_from == "") {
//console.log(aData[column_index]);
return true;
} else {
// debug:
//console.log('arg 1', (new Date(aData[column_index])).getTime());
//console.log('date from', date_from);
//console.log('date to', date_to);
//console.log('truth condition', ((new Date(aData[column_index])).getTime() > date_from && (new Date(aData[column_index])).getTime() < date_to));
/**
* THIS PART MAKES THE FILTER WORK IN SAFARI :)
*/
var parsed = aData[column_index].replace(' ', 'T');
return ((new Date( parsed )).getTime() > date_from && (new Date( parsed )).getTime() < date_to);
}
}
);
};
The above example is intended to work for columns that use a timestamp column value like: <td>2016-08-05 19:14:00</td>

jQuery code works in Firefox but fails in IE

I have a problem that I can't seem to identify, with a code that works perfectly well in Firefox and Chrome but fails in IE.
I have a sequence of the following elements:
<tbody id="tbod161-1__" isloaded="true" style="display: none;"></tbody>
<tbody id="tbod162-2__" isloaded="true"></tbody>
I am trying to create a jQuery cookie, which stores whether the element is visible or not.
function RememberClickedState() {
$('.ms-listviewtable tbody[id^="tbod"]').each(function(){
tid = $(this).attr('id');
var tvisible = ($(this).attr('style') == undefined || $(this).attr('style').indexOf('display: none;') == -1);
var strVisible;
if( tvisible == true)
{
strVisible = "true";
}
if( tvisible == false)
{
strVisible = "false";
}
items += tid+':'+strVisible+';'
})
$.cookie("itemListState", items);
}
When I retrieve the values with:
string = $.cookie("itemListState");
alert(string);
... all the IDs are set to "true" in IE, that means the values were incorrectly written in the cookie. However, this code works perfect when run in Ff / Chrome where some IDs are correctly set to false.
What am I missing?
Thanks,
change:
var tvisible = ($(this).attr('style') == undefined || $(this).attr('style').indexOf('display: none;') == -1);
into:
var tvisible = $(this).is(':visible');
and i have improved your code a bit:
function RememberClickedState() {
$('.ms-listviewtable tbody[id^="tbod"]').each(function(){
var tvisible = $(this).is(':visible');
items += $(this).attr('id')+':'+String(tvisible);
});
$.cookie("itemListState", items.join('; '));
}
You could always try :
function RememberClickedState() {
var items = '';
$('.ms-listviewtable tbody[id^="tbod"]').each(function(i, e) {
items += (e.id + ':' + (e.style.display == 'none'));
});
$.cookie("itemListState", items);
}​
FIDDLE
There is no seperator between the values, and I would probably add a comma by doing this:
function RememberClickedState() {
var items = [];
$('.ms-listviewtable tbody[id^="tbod"]').each(function(i, e) {
items.push(e.id + ':' + (e.style.display == 'none'));
});
$.cookie("itemListState", items.join(', '));
}
FIDDLE

Select portion of input/string instead of all of it

I have an input that holds a date value like so
03/15/2012
I am trying to select only portions of the the value instead of the whole thing. For instance if I click the spot before 2 in 2012 the year 2012 will be selected not the whole date (same for is true for months and day).
This is the code I am working with now
html:
<input class = "date-container" />
javascript/jquery:
$('.date-container').on('select', function (e)
e.preventDefault()
this.onselectstart = function () { return false; };
})
$('.date-container').on('focus', function ()
{
if (document.selection) {
this.focus();
var Sel = document.selection.createRange();
Sel.moveStart('character', -this.value.length);
CaretPos = Sel.text.length;
}
// Firefox support
else if (this.selectionStart || this.selectionStart == '0')
switch (this.selectionStart) {
case 0:
case 1:
this.selectionStart = 0;
this.selectionEnd = 1;
break;
}
}
I have tried a couple things so far. The code above is attempting to prevent the normal select action then based on where the focus is, select a portion of the string(I only have the switch statement options for the month portion, but if it worked I would do the same for day and year). This may be the wrong way to go about it.
Things to note:
By select I mean highlight.
I do not want to use plugins.
This code will select the portion of the date that is clicked on:
$(".date-container").click(function() {
var val = $(this).val();
var sel = this.selectionStart;
var firstSep = val.indexOf("/"), secondSep;
if (firstSep != -1) {
secondSep = val.indexOf("/", firstSep + 1);
if (secondSep != -1) {
if (sel < firstSep) {
this.setSelectionRange(0, firstSep);
} else if (sel < secondSep) {
this.setSelectionRange(firstSep + 1, secondSep);
} else {
this.setSelectionRange(secondSep + 1, val.length);
}
}
}
});​
You can see it work here: http://jsfiddle.net/jfriend00/QV4VT/

Categories