I have fromDate and toDate text boxes and when I select icon beside text boxes Calender will be displayed and when I select a date that date will be displayed in corresponding text boxes.
My intention is to use single generalized function for both toDate and fromDates. How can I do that, I am using YUI Calender and here is my code:
<td>
<strong>From Date</strong>
</td>
<td>
<input type="text" name="fromDate" id="fromDate" value="" size=15>
<img id="calendarFromIcon" src="${resource(dir: "images", file: "calendar_icon.jpg")}" />
<div id="calendarFromContainer"></div>
</td>
<td>
<strong>To Date</strong>
</td>
<td>
<input type="text" name="toDate" id="toDate" value="" size=15>
<img id="calendarToIcon" src="${resource(dir: "images", file: "calendar_icon.jpg")}" />
<div id="calendarToContainer"></div>
</td>
and the script for this is:
var myFromCalendar = new YAHOO.widget.Calendar("calendarFromContainer", {
close: true,
navigator: true
});
myFromCalendar.render();
myFromCalendar.hide();
function handleSelect(type, args, obj) {
var dates = args[0];
var date = dates[0];
var year = date[0];
month = date[1];
month = (month < 10) ? "0" + month : month;
day = date[2];
day = (day < 10) ? "0" + day : day;
var txtDate1 = document.getElementById("fromDate");
txtDate1.value = year+ "/"+ month + "/" + day;
myFromCalendar.hide();
}
myFromCalendar.selectEvent.subscribe(handleSelect,myFromCalendar, true);
YAHOO.util.Event.addListener("calendarFromIcon", "click", function(e) {
var calContainer = YAHOO.util.Dom.get("calendarFromContainer");
var selectedDate = document.getElementById("fromDate");
if (selectedDate.value) {
var matches = selectedDate.value.match(/^\s*0?(\d+)\/0?(\d+)\/(\d+)\s*$/);
var year = parseInt(matches[3]);
var month = parseInt(matches[1]);
var pageDate = month+"/"+year;
myFromCalendar.cfg.setProperty("pagedate", pageDate, false);
myFromCalendar.cfg.setProperty("selected", selectedDate.value, false);
myFromCalendar.render();
}
myFromCalendar.show();
});
You can use jquery to apply a single function to multiple HTML elements. Jqueries select function may help you.
Related
So i have this simple date picker
<input asp-for="D_From" type="date" onchange="myFunction()" id="dfrom" min="1945-01-01" max="9999-12-31" class="form-control">
<input asp-for="D_To" type="date" id="dto" class="form-control">
this is my current script
<script type="text/javascript">
function myFunction() {
var x = document.getElementById("dfrom").value;
document.getElementById("dto").min = x;
}
</script>
i want to set the max to the picked date in dfrom
ex : if dfrom date was 2020-01-01 i want the dto max 2020-01-31
You could achieve this with the following script.
<input asp-for="D_From" type="date" onchange="myFunction()" id="dfrom" min="1945-01-01" max="9999-12-31" class="form-control">
<input asp-for="D_To" type="date" id="dto" class="form-control">
<script type="text/javascript">
function myFunction() {
var x = document.getElementById("dfrom").value;
document.getElementById("dto").min = x;
var month = x.split('-')[1]; // chosen month
var d = new Date(2008, month, 0);
var lastDay = d.getDate(); // last day of month
var maxDate = x.split('-')[0] + '-' + x.split('-')[1] + '-' + lastDay;
document.getElementById("dto").max = maxDate;
}
</script>
There's alot of room for improvements but I hope you get the general idea.
I'm trying to make an alert to user when choose a date. For example, when user choose 2018-09-13, then the alert will show message "7 days later will be 2018-09-20". But instead, the alert message shows 2018-09-137.
<input type="date" name = "date" id = "date" onchange="javascript:var chooseDate=(this.value)+7; alert('7 days later will be '+chooseDate);" >
How should I add days into the date ?? please help, thank you.
this.value will return the date as string using the format YYYY-MM-DD, so if you "add" 7, it will be YYYY-MM-DD7. What you could do is create a new Date object, and then add the days you want, like this:
var chooseDate=new Date(this.value);
chooseDate.setDate(chooseDate.getDate()+7);
alert('7 days later will be '+chooseDate);
This will give you the complete date, though, which is something you probably don't want, so you would have to get the values you actually need, like this:
var chooseDate=new Date(this.value);
chooseDate.setDate(chooseDate.getUTCDate()+7);
var futureDate = chooseDate.getFullYear()+'-'+('0'+(chooseDate.getMonth()+1)).slice(-2)+'-'+('0'+(chooseDate.getDate())).slice(-2);
alert('7 days later will be '+chooseDate);
Here you have a working example:
<input type="date" name = "date" id = "date" onchange="var chooseDate=new Date(this.value);chooseDate.setDate(chooseDate.getUTCDate()+7);var futureDate=chooseDate.getFullYear()+'-'+('0'+(chooseDate.getMonth()+1)).slice(-2)+'-'+('0'+(chooseDate.getDate())).slice(-2);alert('7 days later will be '+futureDate);" >
How about this in :
addDays = function(input_date, days) {
var date = new Date(input_date);
date.setDate(date.getDate() + days);
return date;
}
You then call do addDays(this.value, 7) in onchange().
And, please reference on getDate() and setDate().
You are working with string instead of a date object:
function lPad(val) {
return ((10 > val ? '0' : '') + val);
}
function add(input, unit, value) {
var cur = input.value;
var byValue = Number(value);
if (!/^\d{4}\-\d{2}\-\d{2}$/.test(cur) || !/day|month|year/.test(unit) || isNaN(byValue)) {
console.warn('invalid parameters!');
return false;
}
var dt = new Date(cur.replace(/\-/g, '/'));
if (!dt || isNaN(dt)) {
console.warn('invalid date!');
return false;
}
if ('day' === unit) {
dt.setDate(dt.getDate() + byValue);
} else if ('month' === unit) {
dt.setMonth(dt.getMonth() + byValue);
} else {
dt.setFullYear(dt.getFullYear() + byValue);
}
input.value = [dt.getFullYear(), lPad(1 + dt.getMonth()), lPad(dt.getDate())].join('-');
console.log(cur, value, unit, '=', input.value);
return true;
}
<input type="date" onchange="add(this,'day','+7');" title="+7 days" />
<input type="date" onchange="add(this,'month','-1');" title="-1 month" />
<input type="date" onchange="add(this,'year','+2');" title="+2 year" />
try this one ...
<input type="date" name = "date" id = "date" onchange="ggrr(this)" >
<script>
function ggrr(input){
var dateString = input.value;
var myDate = new Date(dateString);
var d = new Date(Date.parse(myDate));
var y = d.getFullYear();
var da = d.getDate() + 7;
var m = d.getMonth();
console.log(y+':'+m+':'+da);
}
</script>
I want new date range in each box, but it return only last text-box date range. I also made text boxes id's dynamic but still I am facing this issues. I have start date and end date for each text box and I calculated date range in PHP for start date and end date and disabled all those dates which is selected by user in their start date and date all is working fine but it returns last textbox dates disabled in datepicker.
Here is the screenshot-
Sample Image
Javascript function for datepicker to disbaled dates for each box -
$(function () {
var count = $('#count').val();
var uid = $('#usersId').val();
var pid = $('#projectsId').val();
for (i = 1; i <= count; i++) {
$('#projectAssStartDate' + i).datepicker({
beforeShowDay: function (date) {
var dateString = jQuery.datepicker.formatDate('yy-mm-dd', date);
minDate: 0;
alert(dateRange);
console.log(dateString);
return [dateRange.indexOf(dateString) == -1];
}
});
var date_range = $('#calendarDateString' + i).val();
var newdate = date_range.replace(/,(?=[^,]*$)/, '');
var res = '"' + newdate + '"';
var startDate, endDate, dateRange = res;
$('#projectAssEndDate' + i).datepicker({
beforeShowDay: function (date) {
var dateString = jQuery.datepicker.formatDate('yy-mm-dd', date);
console.log(dateString);
return [dateRange.indexOf(dateString) == -1];
}
});
}
});
HTML for create boxes id's dynamic and fetch values from it.
<input type="text" class='datepicker' size='11' title='D-MMM-YYYY' name="projectAssStartDate[]" id="projectAssStartDate<?php echo $id;?>" value="" style="padding: 7px 8px 7px 8px;font-weight: bold;" />
<input type="text" class='datepicker' size='11' title='D-MMM-YYYY' name="projectAssEndDate[]" id="projectAssEndDate<?php echo $id;?>" value="" style="padding: 7px 8px 7px 8px;font-weight: bold;" />
<input id="calendarDateString<?php echo $id;?>" name="calendarDateString<?php echo $id;?>" title='D-MMM-YYYY' type="text" value="<?php echo $string;?>" />
<input id="projectsId" name="projectsId[]" type="hidden" value="<?php echo $rows['PROJECT_ID'];?>" />
<input id="usersId" name="usersId[]" type="hidden" value="<?php echo $rows['UM_ID'];?>" />
Please check the answer and reply whether this is the way you needed it to go. If not please comment what change you want with respect to this below code result. And I'm sorry that I have manipulated few of your values to ease my result. Will give details explanation if this is what you are expecting.
$(function () {
var count = 2;//$('#count').val();
var uid = $('#usersId').val();
var pid = $('#projectsId').val();
// populate the array
var startDatearray= ["index 0","2016-06-15","2016-06-20"]; // you dont need to create this array .. just fetch these dates from your database as u need
var endDatearray=["index 0","2016-06-21","2016-06-25"];
var i;
for (i = 1; i <= count; i++) {
$('#projectAssStartDate' + i).datepicker({
beforeShowDay: function (date) {
var i=parseInt($(this).attr('id').replace(/[^0-9\.]/g, ''), 10); // as i wont get here so i took it from the current id
var startDate = startDatearray[i], // some start date
endDate = endDatearray[i]; // some end date
var dateRange = [];
for (var d = new Date(startDate); d <= new Date(endDate); d.setDate(d.getDate() + 1)) {
dateRange.push($.datepicker.formatDate('yy-mm-dd', d));
}
var dateString = jQuery.datepicker.formatDate('yy-mm-dd', date);
minDate: 0;
//alert(date);
console.log(dateString +"__"+[dateRange.indexOf(dateString) == -1] +"__"+dateRange);
return [dateRange.indexOf(dateString) != -1]; // if u need the opposit then you can use { == -1}
}
});
var date_range = $('#calendarDateString' + i).val();
var newdate = date_range.replace(/,(?=[^,]*$)/, '');
var res = '"' + newdate + '"';
var startDate, endDate, dateRange = res;
$('#projectAssEndDate' + i).datepicker({
beforeShowDay: function (date) {
var dateString = jQuery.datepicker.formatDate('yy-mm-dd', date);
console.log(dateString);
var i=parseInt($(this).attr('id').replace(/[^0-9\.]/g, ''), 10); // as i wont get here so i took it from the current id
var startDate = startDatearray[i], // some start date
endDate = endDatearray[i]; // some end date
var dateRange = [];
for (var d = new Date(startDate); d <= new Date(endDate); d.setDate(d.getDate() + 1)) {
dateRange.push($.datepicker.formatDate('yy-mm-dd', d));
}
var dateString = jQuery.datepicker.formatDate('yy-mm-dd', date);
minDate: 0;
//alert(date);
console.log(dateString +"__"+[dateRange.indexOf(dateString) == -1] +"__"+dateRange);
return [dateRange.indexOf(dateString) != -1]; // if u need the opposit then you can use { == -1}
}
});
}
});
I have two date fields. Field 2 works fine. Clicking anywhere on the input type date for second fields opens the calendar. But the same is not working for first date field. When I click on the calendar icon for date field it opens the calendar but I want that calendar should pop up when I click anywhere on the date field for field 1 as well.
Why does it works for the second field but not for the first field.
Also the default date is not getting set to todays date.
http://jsfiddle.net/KJ4e5/3/
HTML
<body>
<div id="doc">
<table>
<tr>
<td>
<input name="date1" id="date1" type="date" data-role="datebox" data-options='{"mode": "calbox","dateFieldOrder":["d","m","y"], "useNewStyle":true,"overrideDateFormat": "%d/%m/%Y", "afterToday":true}' />
</td>
<td>
<input name="date2" id="date2" type="date" data-role="datebox" data-options='{"mode": "calbox","dateFieldOrder":["d","m","y"], "useNewStyle":true,"overrideDateFormat": "%d/%m/%Y", "afterToday":true}'/>
</td>
</tr>
</table>
</div></body>
//JS
$( document ).on( "pageinit", "#doc", function() {
var defaultPickerValue = new Date();
var today = defaultPickerValue.getDate() + "/" + (defaultPickerValue.getMonth()+1) + "/" + defaultPickerValue.getFullYear();
$('#date1').val(today);
$('#date2').val(today);
$('#date1').on('change', function() {
if ( $('#date2')) {
$('#date2').val($('#date1').val());
var temp = new Date();
var start = $('#date1').datebox('getTheDate');
var diff = parseInt((start - temp) / ( 1000 * 60 * 60 * 24 ));
diffstrt = (diff * -1)-1;
$("#date2").datebox("option", {
"minDays": diffstrt
});
}
});
});
I can't explain why the 2 boxes act differently, but if you explicitly assign the useFocus option to the boxes, they will both work:
<input name="date1" id="date1" type="date" data-role="datebox"
data-options='{"mode": "calbox","dateFieldOrder":["d","m","y"],
"useNewStyle":true, "overrideDateFormat": "%d/%m/%Y",
"afterToday":true, "centerHoriz": true, "useFocus": true}' />
Here is your updated FIDDLE
In the fiddle I have also changed your script a little. With the datebox you can set the dates as follows:
var defaultPickerValue = new Date();
$('#date1').datebox('setTheDate', defaultPickerValue).trigger('datebox', {'method':'doset'});
$('#date1').on('change', function () {
if ($('#date2')) {
var temp = new Date();
var start = $('#date1').datebox('getTheDate');
$('#date2').datebox('setTheDate', start).trigger('datebox', {'method':'doset'});
var diff = parseInt((start - temp) / (1000 * 60 * 60 * 24));
diffstrt = (diff * -1) - 1;
$("#date2").datebox("option", {
"minDays": diffstrt
});
}
});
I want to disable specific day dynamically but when I pass any variable to beforeShowDay function in jQuery calendar in php it gives error.
var disableSpecificWeekDays = function(dt) {
//0= sunday 1=monday 2=tuesday 3=wednesday 4=thursday 5=friday 6=saturday
var daysToDisable=[0];
return (dt.getDay() !== daysToDisable);
};
Try:
CODE:
var unavailableDates = new Array();
function unavailable(date) {
dmy = date.getDate() + "-" + (date.getMonth() + 1) + "-" + date.getFullYear();
if ($.inArray(dmy, unavailableDates) == -1) {
return [true, ""];
} else {
return [false, "", "Unavailable"];
}
}
$(function() {
$("#btn").click(function(){
unavailableDates.push($("#txt1").val());
unavailableDates.push($("#txt2").val());
unavailableDates.push($("#txt3").val());
alert(unavailableDates);
});
$("#iDate").datepicker({
dateFormat: 'dd MM yy',
beforeShowDay: unavailable
});
});
HTML
<input id="txt1" type="text"></input>
<input id="txt2" type="text"></input>
<input id="txt3" type="text"></input>
<input id="btn" type="button" value="Click me to disable dates"></input>
<input id="iDate">
FIDDLE
NOTE:
Here I used three inputs to read dates and button to add those in array. You can change this according to your requirement.