On a landing page a datepicker is loaded as you can see in the image. I want to be able to change the background colors of specific dates on the calendar.
For example :
If 27-11-2017 slot is booked, then on load I want the color to change for that date.
My Script code:
<script>
$(document).ready(function () {
// I am getting a data on this loop so how can i change same date background color
#if(!empty($BookeData))
#foreach($BookeData as $key => $value)
#if($value->event_date)
#endif
#endforeach
#endif
/* Gt data in $BookeData
array:13 [
"id" => 8
"source_type" => "App\Venue"
"source_id" => 7
"event_date" => "2017-11-28"
"session" => "1"
"payment" => "5000"
"status" => "Booked"
"created_at" => "2017-11-27 10:30:22"
"updated_at" => "2017-11-27 10:30:22"
]*/
var date = new Date();
var today = new Date(date.getFullYear(), date.getMonth(), date.getDate());
$('#datepicker').datepicker({
changeYear: true,
multidate :true,
maxViewMode: 0,
startDate: today
}).on('changeDate', function(e) {
var $date = $.datepicker.formatDate('yy-mm-dd', e.date);
$("#event_date").val($date);
//e.preventDefault();
//var formData = $('form').serialize();
$.ajax({
type: 'GET',
url: "{{ route('admin.calendar.add') }}",
data: {'date':$date},
cache: false,
success: function(response){
$("#calendar div.divForm").html(response);
$("<input type='hidden' value='' name='event_date' id='event_date' />").appendTo('#calendar div.dateDiv');
$("#event_date").val($date);
$("#calendar").show();
}
});
});
$(".close").on("click", function() {
$("#calendar").hide();
});
});
As i understand your issue, try as like below:
<input type="text" id="datepicker" />
var booked_date = ["27/11/2017"]; //Take your booked date here from your data
$("#datepicker").datepicker({
format: "dd/mm/yyyy",
autoclose: true,
todayHighlight: true,
beforeShowDay: function(date){
var d = date;
var curr_date = d.getDate();
var curr_month = d.getMonth() + 1; //Months are zero based
var curr_year = d.getFullYear();
var formattedDate = curr_date + "/" + curr_month + "/" + curr_year
if ($.inArray(formattedDate, booked_date) != -1){
return {
classes: 'activeClass'
};
}
return;
}
});
The activeClass can be any form of CSS. In my example i have just changed the background color. In your example you could offset an image and apply it to the day.
.activeClass{
color: yellow;
background: white;
}
Hope this helps you OR you can get some idea!
Related
Pretty new here, so sorry if the solutions are a bit "obvious":)
I'm using a datepicker/calendar of "formatic UI", dealing with two issues:
When clicking the input, the pop-up picker is out off screen. I've tried to fix it with css positions (also a bit js) but really stack how to do it only to the pop up picker and not to the input. Also, my language is Hebrew so there might be a problem regarding to rtl issues (I've tried a rtl CDN, still was not that helpful=/)
This picker is used to filter my data. The problem is when a user click on the popup picker, the picker is changed, but only when clicking again the input, data is filtered. Filtering function supposed to be on "keyup, click, change" but still, not working when value is changed. (for other inputs- when value is changed - it indeed working. Only this picker has an issue)
my code:
$(document).ready(function () {
$('#start_date_picker,#end_date_picker').on("keyup click change", filterAll);
});
var today = new Date();
$('#rangestart').calendar({
type: 'date',
endCalendar: $('#rangeend'),
text: {
days: ['א', 'ב', 'ג', 'ד', 'ה', 'ו', 'ש'],
months: ['ינואר', 'פברואר', 'מרץ', 'אפריל', 'מאי', 'יוני', 'יולי', 'אוגוסט', 'ספטמבר', 'אוקטובר', 'נובמבר', 'דצמבר'],
monthsShort: ['ינ', 'פב', 'מרץ', 'אפר', 'מאי', 'יונ', 'יול', 'אוג', 'ספט', 'אוק', 'נוב', 'דצמ'],
today: 'היום',
now: 'כעת'
},
minDate: new Date(today.getFullYear(), today.getMonth(), today.getDate() ),
monthFirst: false,
formatter: {
date: function (date, settings) {
if (!date) return '';
var day = date.getDate();
var month = date.getMonth() + 1;
var year= date.getFullYear().toString().substr(-2);
return day + '.' + month + '.' + year;
}
}
});
$('#rangeend').calendar({
type: 'date',
startCalendar: $('#rangestart'),
text: {
days: ['א', 'ב', 'ג', 'ד', 'ה', 'ו', 'ש'],
months: ['ינואר', 'פברואר', 'מרץ', 'אפריל', 'מאי', 'יוני', 'יולי', 'אוגוסט', 'ספטמבר', 'אוקטובר', 'נובמבר', 'דצמבר'],
monthsShort: ['ינ', 'פב', 'מרץ', 'אפר', 'מאי', 'יונ', 'יול', 'אוג', 'ספט', 'אוק', 'נוב', 'דצמ'],
today: 'היום',
now: 'כעת'
},
monthFirst: false,
formatter: {
date: function (date, settings) {
if (!date) return '';
var day = date.getDate();
var month = date.getMonth() + 1;
var year= date.getFullYear().toString().substr(-2);
return day + '.' + month + '.' + year;
}
}
});
var start_date_picker = document.getElementById('start_date_picker');
var end_date_picker = document.getElementById('end_date_picker');
var month_picker_start = today.getMonth()+1;
var year_picker_start= today.getFullYear().toString().substr(-2);
var week_from_today = new Date();
week_from_today.setDate(week_from_today.getDate() + 7);
var month_week_from_today = week_from_today.getMonth()+1;
var year_from_today= week_from_today.getFullYear().toString().substr(-2);
if(start_date_picker) {start_date_picker.value = today.getDate()+ "." + month_picker_start+ "." + year_from_today;}
if(end_date_picker) {end_date_picker.value = week_from_today.getDate()+ "." +month_week_from_today + "." + year_from_today;}
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/semantic-ui#2.4.2/dist/semantic.min.css">
<script src="https://cdn.jsdelivr.net/npm/semantic-ui#2.4.2/dist/semantic.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui-calendar/0.0.8/calendar.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui-calendar/0.0.8/calendar.min.css" />
<i class="ui calendar" id="rangestart">
<div class="ui transparent input right icon">
<i class="calendar alternate outline icon grey icon"></i>
<input type="text" id="start_date_picker" style="text-align:right;">
</div>
</i>
-
<i class="ui calendar" id="rangeend">
<div class="ui transparent input right icon">
<input type="text" id="end_date_picker" style="text-align:right;">
</div>
</i>
I'm trying to set a date for date-picker on selecting date from first date-picker, and want to show an alert message if user selected another date. I'm not able to do that.
Here is my code:
$('#ELEdatepicker1').datepicker({
autoclose: true,
endDate: new Date(),
todayHighlight: true,
}).change(function(){
getELEdifference($(this),$('#ELEdatepicker2'));
});
$('#ELEdatepicker2').datepicker({
autoclose: true,
startDate: new Date(),
todayHighlight: true,
}).change(function(){
getELEdifference($('#ELEdatepicker1'),$(this));
alert('Are you sure ?');
});
function getELEdifference($this1,$this2)
{
if($this1.datepicker("getDate") != null && $this2.datepicker("getDate") != null)
{
var ELEcertDiff= $this1.datepicker("getDate") - $this2.datepicker("getDate");
var result = ELEcertDiff / (1000 * 60 * 60 * 24) * -1;
//$("#ELEcertDiff").text(result);
document.getElementById("ELEcertDiff").value = result;
}
}
How can I show a date (suppose one year latter) in second date-picker ? And if user select before or after one year, it will show alert message on date selection.
UPDATE:
Is it possible to pass a parameter to set a difference for second date picker?
For Ex.
In above picture If I select a date from Issue Date-picker and from duration drop-down list box select a value (Ex. 3), then in Expiry Date-picker shows date after 3 years from selected date.
I've referred some questions:
Jquery UI : date picker. How to set date in date picker by $_GET
Define start date of second date picker from first date picker
I'm new to JavaScript and JQuery. Any kind of help is welcome. Thanks in advance.
plz add and check this code:
$('#ELEdatepicker1').datepicker({
autoclose: true,
todayHighlight: true,
dateFormat:'dd-mm-yy',
onClose: function( selectedDate ) {
var d = new Date(selectedDate);
var day = d.getDate();
var month = d.getMonth();
var year = d.getFullYear() + 1;
var newdate = month + "-" + day + "-" + year;
$( "#ELEdatepicker2" ).datepicker( "option", "minDate", newdate );
$('.highlight a', $(this).next()).addClass('ui-state-highlight');
}
});
$('#ELEdatepicker2').datepicker({
autoclose: true,
todayHighlight: true,
dateFormat:'dd-mm-yy',
onClose: function( selectedDate ) {
$("#ELEdatepicker2" ).datepicker( "option", "maxDate", selectedDate );
$('.highlight a', $(this).next()).addClass('ui-state-highlight');
}
});
Check this answer
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<input type="text" id="ELEdatepicker1">
<input type="text" id="ELEdatepicker2">
<!-- <input type="text" id="ELEcertDiff"> -->
<script>
$('#ELEdatepicker1').datepicker({
autoclose: true,
todayHighlight: true,
dateFormat:'dd-mm-yy',
onClose: function( selectedDate ) {
var d = new Date(selectedDate);
var year = d.getFullYear() + 1;
var month = d.getMonth();
var day = d.getDate();
var newdate = year + "-" + month + "-" + day;
$( "#ELEdatepicker2" ).datepicker( "option", "minDate", newdate );
$('.highlight a', $(this).next()).addClass('ui-state-highlight');
}
});
$('#ELEdatepicker2').datepicker({
autoclose: true,
todayHighlight: true,
dateFormat:'dd-mm-yy',
onClose: function( selectedDate ) {
$("#ELEdatepicker2" ).datepicker( "option", "maxDate", selectedDate );
$('.highlight a', $(this).next()).addClass('ui-state-highlight');
}
});
</script>
I am fairly new to JavaScript and through few tutorials have been able to put the following code together for the jQuery date picker. However, I need to be able to store disabled dates in a variable which will be the result of a query.
I also need to prevent someone from booking through disabled dates, therefore if 3/3/15 is disabled someone can't select from 2/3/15 to 3/3/15.
Below is the code which I have in my JS file. Any help would be appreciated.
$(document).ready(function() {
var bookedDays = ["2015-2-27","2015-2-28","2010-6-14"];
***Should be results of select from table query.
e.g SELECT fromdate, todate from table where id = $_GET['id']***
$('#request').hide();
$('.days').html('Please select a date range of at least the same day. <br/> <i>Max booking: 2 Months.</i>');
$( "#from" ).datepicker({
defaultDate: new Date(),
changeMonth: true,
numberOfMonths: 1,
minDate: new Date(),
maxDate: "+1M",
beforeShowDay: isAvailable,
onClose: function( selectedDate ) {
var day = $("#from").datepicker('getDate');
day.setDate(day.getDate()+1);
$( "#to" ).datepicker( "option", "minDate", day );
}
});
$( "#to" ).datepicker({
defaultDate: new Date(),
changeMonth: true,
numberOfMonths: 1,
minDate: ("#to"),
maxDate: "+2M",
beforeShowDay: isAvailable,
onClose: function( selectedDate ) {
$( "#from" ).datepicker( "option", "maxDate", selectedDate );
}
});
function isAvailable(date){
var dateAsString = date.getFullYear().toString() + "-" + (date.getMonth()+1).toString() + "-" + date.getDate();
var result = $.inArray( dateAsString, bookedDays ) ===-1 ? [true] : [false];
return result;
}
$('#to').on('change',function(){
var days = (daydiff(parseDate($('#from').val()), parseDate($('#to').val())));
var cogs = $('#cogsday').html();
cogs = cogs.replace(/\D/g,'');
var x = days;
var y = cogs * x;
$('.days').html('You have chosen to borrow this item for <b>'+ days + '</b> days at a cost of <b>' + y + '</b> cogs.<br/><br/>');
if(days){
$('#request').show();
}
$('#request').click(function() {
var cogs = $('#cogsday').html();
cogs = cogs.replace(/\D/g,'');
var x = days ;
var y = cogs * x;
$('#total').text(y);
$('#nameID').val(y);
$('#days').text(days);
$('#daysID').val(days);
});
})
function parseDate(str) {
var mdy = str.split('/')
return new Date(mdy[2], mdy[0]-1, mdy[1]);
}
function daydiff(first, second) {
return Math.round((second-first)/(1000*60*60*24));
}
});
I have a registration form, where people can select multiple dates selected from a database. I use the jQuery UI Datepicker. Everything works fine, but when I submit the form it saves me the date itself like this : "09/16/2012,08/04/2011,04/19/1994". I would like to store the ID of the date instead.
Does anyone know how to get the ID of the selected date, and put it in the value="" attribute?
<input type="text" class="datepicker" name="live[]" value="">
<script>
var dates = [<?php $i=0; while($dataDate = mysql_fetch_object($dates)) : echo ($i>0) ? ", " : ""; echo '"'.date("n-j-Y", strtotime($dataDate->date)).'"'; $i++; endwhile;?>];
var enabledDays = dates;
function enableAllTheseDays(date) {
var m = date.getMonth(), d = date.getDate(), y = date.getFullYear();
for (i = 0; i < enabledDays.length; i++) {
if($.inArray((m+1) + '-' + d + '-' + y,enabledDays) != -1) {
return [true];
}
}
return [false];
}
$('.datepicker').datepicker({
beforeShowDay: enableAllTheseDays,
yearRange: "1994:2012",
changeMonth: true,
changeYear: true
});
</script>
Okay so heres totally new aproach to get desired outcome.
first of all, put the dates in json obejct.
make your SQL query select id, date from database
now if you have php json available, just use
<?php
while($row = mysql_fetch_object($query) ) {
$data[] = array( "id" => $row['id'], "date" => $row['date'] );
}
echo "var dates = [" . json_encode($data) . "];";
?>
otherwise you can do it like this:
<?php
echo "var dates = [";
while($row = mysql_fetch_object($query) ) {
$data[] = '{"id" : "' .$row["id"] . '", "date" : "' . $row["date"] . '" }';
}
echo implode(',', $data);
echo "];";
?>
Now we got json object which should look like
[{"id" : "12", "date": "2012-02-01"},{"id" : "33", "date": "2012-02-03"}]
i tweaked your function little bit, to work with our json object
function enableAllTheseDays(date) {
var m = date.getMonth(), d = date.getDate(), y = date.getFullYear();
var datestr = y + "-" + m + "-" + d;
for (i = 0; i < dates.length; i++) {
if( dates[i].date == datestr) {
return [true];
}
}
return [false];
}
$('.datepicker').datepicker({
beforeShowDay: enableAllTheseDays,
yearRange: "1994:2012",
changeMonth: true,
changeYear: true
});
Now back to getting the id
$('.datepciker').on('change',function() {
for(var i = 0; i < dates.length; i++) {
if( dates[i].date == $(this).val() )
var index = dates[i].id;
}
$("#date_id_holder").val( index );
});
and now your $("#date_id_holder") contains the id of selected date
I am comparing some dropdownlist value, basically the Start date must be earlier than end date
I found a lot of sample source codes through goggle and others, but they only provide DD/MM/YYYY. I only need MM/YYY only, when ever i tried to remove "DD" there would be errors, if i am right its because of the date keyword/element.
Is there any solution to it? any help or ref link would be good. Thanks
P.s The codes below are working for DD/MM/YYYY
function y2k(number) {
return (number < 1000) ? number + 1900 : number;
}
function padout(number) {
return (number < 10) ? '0' + number : number;
}
function validate(what) {
var startday = what.startday.options[what.startday.selectedIndex].value;
var startmonth = what.startmonth.options[what.startmonth.selectedIndex].value;
var startyear = what.startyear.options[what.startyear.selectedIndex].text;
var endday = what.endday.options[what.endday.selectedIndex].value;
var endmonth = what.endmonth.options[what.endmonth.selectedIndex].value;
unvalidstartdate = startday + '/' + startmonth + '/' + startyear;
unvalidenddate = endday + '/' + endmonth;
var startdate = new Date(startyear - 0, startmonth - 1, startday - 0);
var enddate = new Date(endmonth - 1, endday - 0);
var validstartdate = padout(startdate.getDate()) + '/'
+ padout(startdate.getMonth() + 1) + '/'
+ y2k(startdate.getYear())
var validenddate = padout(enddate.getDate()) + '/'
+ padout(enddate.getMonth() + 1) + '/' + y2k(enddate.getYear());
if (unvalidstartdate != validstartdate) {
alert('Start Date: '
+ what.startday.options[what.startday.selectedIndex].text
+ ' '
+ what.startmonth.options[what.startmonth.selectedIndex].text
+ ' '
+ what.startyear.options[what.startyear.selectedIndex].text
+ ' is invalid');
return false;
}
if (unvalidenddate != validenddate) {
alert('End Date: '
+ what.endday.options[what.endday.selectedIndex].text + ' '
+ what.endmonth.options[what.endmonth.selectedIndex].text
+ ' '
+ ' is invalid');
return false;
}
starttime = Date.UTC(y2k(startdate.getYear()), startdate.getMonth(),
startdate.getDate(), 0, 0, 0);
endtime = Date.UTC(y2k(enddate.getYear()), enddate.getMonth(), enddate
.getDate(), 0, 0, 0);
if (starttime < endtime) {
alert('VALID');
// valid
} else {
alert('NOT VALID');
return false;
}
currentdate = new Date();
currenttime = Date.UTC(y2k(currentdate.getYear()), currentdate
.getMonth(), currentdate.getDate(), 0, 0, 0);
if (endtime < currenttime) {
// valid
} else {
alert('End Date is not less than todays date');
return false;
}
what.startdate.value = validstartdate;
what.enddate.value = validenddate;
return true;
}
//-->
</script>
<form>
Start Date: <select name="startday">
<option value="01">1st
<option value="02">2nd
<option value="03">3rd
</select> <select name="startmonth">
<option value="01">january
<option value="02">february
<option value="03">march
</select> <select name="startyear">
<option>1990
<option>1991
<option>1992
</select>
<p>
End Date: <select name="endday">
<option value="01">1st
<option value="02">2nd
<option value="03">3rd
</select> <select name="endmonth">
<option value="01">january
<option value="02">february
<option value="03">march
</select> <input type="hidden" name="startdate"> <input type="hidden"
name="enddate">
<p>
<input type="button" onClick="validate(this.form)" value="Validate">
</form>
var startDateFinal = "your startdate element value";
var endDateFinal = "your enddate element value";
var startDate = new Date (startDateFinal);
var endDate = new Date(endDateFinal);
if(endDate.getTime() > startDate.getTime()){
// some logic
}
else{
// some logic
}
var invalid=false;
var startDate="03/2011";//start date in mm/yyyy format
var endDate="04/2012";//end date in mm/yyyy format
var startMonth=startDate.substring(0,2);
var endMonth=endDate.substring(0,2);
var startYear=startDate.substring(3);
var endYear=endDate.substring(3);
if(startYear>endYear)
{
invalid=true;
}
else if(startYear<endYear && startMonth>endMonth)
invalid=true;
The Date constructor only needs year and month and you can use strings, so you can use the values directly from the form controls like:
var start = new Date(startyear, --startmonth);
var end = new Date(endyear, --endmonth);
if (start < end) {
// start is before end
}
Oh, and you should be using getFullYear to get the full year number. For compatibility with Java, the original getYear method only returns a two digit year.
The below code will give you two date fields the start date field will be smaller than end date field. the code works fine
you will get the jquery, jqueryui/calendar on http://jquery.com/ and http://jquery.com/ sites.
include below code in HEAD section
include jquery-1.5.1.min.js, jquery-ui-1.8.13.custom.min.js, jquery-ui-1.8.11.custom.css" ,calendar.css" files
$(function() {
var dates = $( "#txt_startdate, #txt_enddate" ).datepicker({
defaultDate: "+1w",
changeMonth: true,
changeYear: true,
numberOfMonths: 2,
dateFormat: 'yy-mm-dd',
onSelect: function( selectedDate ) {
var option = this.id == "txt_startdate" ? "minDate" : "maxDate",
instance = $( this ).data( "datepicker" ),
date = $.datepicker.parseDate(
instance.settings.dateFormat ||
$.datepicker._defaults.dateFormat,
selectedDate, instance.settings );
dates.not( this ).datepicker( "option", option, date );
}
});
});
enter below code in body section of your html
<input name="txt_startdate" id="txt_startdate" type="text" />
<input name="txt_enddate" id="txt_enddate" type="text" />
Hope this helps you
try this
function test()
{
var date1,date;
date1 = new Date(2011,11,1);
// startdate drop down values
//2011-->year 11--> startmonth 1-->startdate(this you keep always as 1 for startdate and end date) since you only wants to compare mm/yyyy
date2 = new Date(2002,11,1);
// enddate drop down values
//2011-->year 11--> endmonth 1-->enddate(this you keep always as 1 for startdate and end date) since you only wants to compare mm/yyyy
if(date1>date2)
alert("date1 is > date2")
else
alert("date2 is > date1")
}
check this date