I have a page where adding new record in the database is the main function. the page is working fine after one condition is given. one of the fields that is required to be added is the date field. the page has a dropdown of year date (2017,2018.2019). when the selected year in the dropdown for example is 2017, all input should be the date within 2017. inputted date that is less or greater than 2017 should not be validated and not accepted. this goes the same when the selected year in the dropdwon is 2018 or 2019. accepted input should be the same of the selected year in the dropdown.
I initially used Jquery validate to do the validation.(im just showing the date part in the validation)
here is the html for the dropdown
<div class="col-sm-2" id="y_type" style="text-align:left;">
<select class="" style="width: 100%; display:inline-block;">
#{
DateTime datetime = DateTime.Now;
for (int i = 0; i <= 2; i++)
{
<option>#(datetime.AddYears(+i).ToString("yyyy"))</option>
}
}
</select>
</div>
holiday_date in the id of the textfield on the other hand,
here's the jquery part that does the validation before
$("form").validate({
rules:
{
"holiday_date[]": {
required: true
},
},
},
errorClass: "invalid",
errorPlacement: function (error, element) {
$('#ResultDialog p').html("#hmis_resources.Message.msg_80005");
$('#ResultDialog').modal();
},
submitHandler: function (form) {
ajaxFormSubmit();
}
});
What I initially do is create a function that test or compare the textfield of date and the value of the dropdown. But this does not work either. and i am not sure of its placing
function testdate() {
$(".holidayBody tr").each(function (key, value) {
var holiday_date = $(value).find(".holiday_date").val();
if (typeof holiday_date !== 'undefined') {
var year = holiday_date.substr(6, 4);
var month = holiday_date.substr(3, 2);
var days = holiday_date.substr(0, 2)
holiday_date = year + '/' + month + '/' + days;
var dropdownear = $('#y_type :selected').text();
var result = year == dropdownear;
alert(result)
}
})
}
if there is a simpler way to accomplish this, i would appreciate if you can share.
You should add a custom method for the validator, like in this fiddle:
Validating year from select input.
<script>
$(document).ready(function() {
var $select = $("select");
//I added only the year to the drop down, you should change it to full date.
for (var i = 0; i < 3; i++) {
var year = new Date();
year.setFullYear(year.getFullYear() + i);
$select.append("<option value=" + year.getFullYear() + " >" + year.getFullYear() + " </option>");
}
// add the rule here
$.validator.addMethod("thisYearOnly", function(value, element, arg) {
var selectedYear = value;
var currentDate = new Date();
var currentYear = currentDate.getFullYear();
return currentYear == selectedYear;
}, "Must select this year");
// configure your validation
$("form").validate({
rules: {
mydate: {
thisYearOnly: true
}
}
});
});
</script>
Related
I have a textbox which allows users to choose a date from a calendar in mm/dd/yyyy format. I used the pikaday and moment libraries to achieve this. Now, if the user selects a date that is not in the future, I want to show an error in a label saying that the date is invalid. What is the 'best' way to achieve this? Working with dates in Javascript turned out to be quite a headache.I have provided my current approach:
textbox:
<asp:TextBox ID="txtDepartureDate" runat="server" ForeColor="Gray" onfocus="txtOnFocusDeparture(this)" onblur="txtOnBlurDeparture(this)" oninput="oninputDeparture()" AutoPostBack="True">DEPARTURE DATE</asp:TextBox>
script:
<script type="text/javascript">
function oninputDeparture() {
var inputDate = moment(document.getElementById('txtDepartureDate').value, 'DD/MM/YYYY');
var todayDate = moment().format('DD/MM/YYYY');
var lblError = document.getElementById('lblError');
var daysDiff = todayDate.diff(inputDate, 'days');
if (daysDiff <= 0) {
lblError.innerText = "Departure Day should be after today";
}
else {
lblError.innerText = "";
}
}
</script>
var todayDate = moment().format('DD/MM/YYYY');
var lblError = document.getElementById('lblError');
var daysDiff = todayDate.diff(inputDate, 'days');
moment.diff requires a moment object. todayDate is assigned as string in this case.
Also consider quick exit when the user is still typing
Have a look at the example.
var dateInput = document.getElementById('txtDepartureDate');
var lblError = document.getElementById('lblError');
function setError(text) {
lblError.innerText = text
}
function oninputDeparture() {
var value = dateInput.value;
var dateValue = moment(value, 'DD/MM/YYYY');
if (value.length < 10 || !dateValue.isValid()) {
return;
}
var todayDate = moment();
var daysDiff = todayDate.diff(dateValue, 'days');
if (daysDiff >= 0 && !dateValue.isAfter(todayDate, 'days')) {
setError("Departure Day should be after today");
} else {
setError("");
}
}
setTimeout(() => {
dateInput.value = moment().add(1, 'days').format('DD/MM/YYYY')
oninputDeparture()
}, 1000)
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.19.1/moment.min.js"></script>
<input id="txtDepartureDate" type="text" oninput="oninputDeparture()" />
<div id="lblError"></div>
I have this code which you can select date and get results according to it. Now in the place of months and years selection i want a button that shows previous month and another button that shows next month. Like that Next day and previous day. Can someone please help me with this code snippet.
1. Button one - Previous month
2. Button two - Next month
3. Button three - Previous Day
4. Button four - Next Day
All results should be on HTML page.
<HTML>
<HEAD>
<TITLE></TITLE>
<STYLE TYPE="text/css">
TD, TH {text-align:center}
</STYLE>
<SCRIPT LANGUAGE="JavaScript">
function getFirstDay(theYear, theMonth){
var firstDate = new Date(theYear,theMonth,1)
return firstDate.getDay()
}
function getMonthLen(theYear, theMonth) {
var oneDay = 1000 * 60 * 60 * 24
var thisMonth = new Date(theYear, theMonth, 1)
var nextMonth = new Date(theYear, theMonth + 1, 1)
var len = Math.ceil((nextMonth.getTime() -
thisMonth.getTime())/oneDay)
return len
}
var theMonths = ["January","February","March","April","May","June","July","August",
"September","October","November","December"]
function getObject(obj) {
var theObj
if (document.all) {
if (typeof obj == "string") {
return document.all(obj)
} else {
return obj.style
}
}
if (document.getElementById) {
if (typeof obj == "string") {
return document.getElementById(obj)
} else {
return obj.style
}
}
return null
}
function populateTable(form) {
var theMonth = form.chooseMonth.selectedIndex
var theYear = parseInt(form.chooseYear.options[form.chooseYear.selectedIndex].text)
// initialize date-dependent variables
var firstDay = getFirstDay(theYear, theMonth)
var howMany = getMonthLen(theYear, theMonth)
// fill in month/year in table header
getObject("tableHeader").innerHTML = theMonths[theMonth] +
" " + theYear
// initialize vars for table creation
var dayCounter = 1
var TBody = getObject("tableBody")
// clear any existing rows
while (TBody.rows.length > 0) {
TBody.deleteRow(0)
}
var newR, newC
var done=false
while (!done) {
// create new row at end
newR = TBody.insertRow(TBody.rows.length)
for (var i = 0; i < 7; i++) {
// create new cell at end of row
newC = newR.insertCell(newR.cells.length)
if (TBody.rows.length == 1 && i < firstDay) {
// no content for boxes before first day
newC.innerHTML = ""
continue
}
if (dayCounter == howMany) {
// no more rows after this one
done = true
}
// plug in date (or empty for boxes after last day)
newC.innerHTML = (dayCounter <= howMany) ?
dayCounter++ : ""
}
}
}
function fillYears() {
var today = new Date()
var thisYear = today.getFullYear()
var yearChooser = document.dateChooser.chooseYear
for (i = thisYear; i < thisYear + 5; i++) {
yearChooser.options[yearChooser.options.length] = new Option(i, i)
}
setCurrMonth(today)
}
// set month choice to current month
function setCurrMonth(today) {
document.dateChooser.chooseMonth.selectedIndex = today.getMonth()
}
</SCRIPT>
</HEAD>
<BODY onLoad="fillYears(); populateTable(document.dateChooser)">
<H1>Calender</H1>
<HR>
<TABLE style="width:100%;height:80%;" ID="calendarTable" BORDER=1 ALIGN="center">
<TR>
<TH ID="tableHeader" COLSPAN=7></TH>
</TR>
<TR><TH>Sun</TH><TH>Mon</TH><TH>Tue</TH><TH>Wed</TH>
<TH>Thu</TH><TH>Fri</TH><TH>Sat</TH></TR>
<TBODY ID="tableBody"></TBODY>
<TR>
<TD COLSPAN=7>
<P>
<FORM NAME="dateChooser">
<SELECT NAME="chooseMonth"
onChange="populateTable(this.form)">
<OPTION SELECTED>January<OPTION>February
<OPTION>March<OPTION>April<OPTION>May
<OPTION>June<OPTION>July<OPTION>August
<OPTION>September<OPTION>October
<OPTION>November<OPTION>December
</SELECT>
<SELECT NAME="chooseYear" onChange="populateTable(this.form)">
</SELECT>
</FORM>
</P></TD>
</TR>
</TABLE>
</BODY>
</HTML
I suggest to use moment.js. It helps alot when you work with time and date.
e.g. after pressing a button "next month" you can use moment().add(1, 'months') to add 1 month to your current date. you can store the date after switching e.g. on data attributes or hidden input or ...
complete documentation you can find on https://momentjs.com/docs/
So I am using the air-datepicker (http://t1m0n.name/air-datepicker/docs/)
to select a month, presetting to 01/03/2018 for example, which fills a hidden field in my input called startdate2 using the altmethod.
What I want is to update enddate2 with startdate2 + 2 months. I've tried using onChange and a few various methods but nothing seems to be working.
<input type="hidden" name="startdate" id="startdate2" value="" class="inputdate" onChange="getDateAhead()" >
<input type="hidden" name="enddate" id="enddate2" value="" class="outputdate" >
<script>
function getDateAhead()
{
var start = document.getElementById('startdate2').value;
var end = start.setMonth(start.getMonth()+2);
document.getElementById('enddate2').value = end;
}
</script>
Just can't seem to get it working??
Please check documentation(http://t1m0n.name/air-datepicker/docs/) for the datepicker you are using. Your concern function is onSelect.
var eventDates = [1, 10, 12, 22],
$picker = $('#custom-cells'),
$content = $('#custom-cells-events'),
sentences = [ … ];
$picker.datepicker({
language: 'en',
onRenderCell: function (date, cellType) {
var currentDate = date.getDate();
// Add extra element, if `eventDates` contains `currentDate`
if (cellType == 'day' && eventDates.indexOf(currentDate) != -1) {
return {
html: currentDate + '<span class="dp-note"></span>'
}
}
},
onSelect: function onSelect(fd, date) {
var title = '', content = ''
// If date with event is selected, show it
if (date && eventDates.indexOf(date.getDate()) != -1) {
title = fd;
content = sentences[Math.floor(Math.random() * eventDates.length)];
}
$('strong', $content).html(title)
$('p', $content).html(content)
}
})
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 function that loops every 500ms, and collects date information:
var mlptoday = {};
var timer = setTimeout(today,500);
function today(){
var d = new Date()
mlptoday.date = checkTime(d.getDate()); //output: "27"
mlptoday.year = d.getFullYear(); //output: "2013"
mlptoday.month = checkTime(d.getMonth()+1); //output: "01"
}
function checkTime(i) { if (i<10){i="0" + i} return i }
In a different function, I would like to check if the date the user gives as input is either the same day, or after the given day.
An example input may be: 2013.01.27.
I use this snippet of code to achieve what I want:
var remTime = "2013.01.27"; //user input
var remTimeArray = remTime.split('.') //output: ["2013","01","27"]
if (
!(remTimeArray[0] >= parent.mlptoday.year &&
remTimeArray[1] >= parent.mlptoday.month) ||
!((remTimeArray[1] == parent.mlptoday.month) ? Boolean(remTimeArray[2]*1 >= parent.mlptoday.date) : true)
){
//the input date is in the past
}
As you could probably guess, this does not work. The conditional statement seems to fail me, because if I invert Boolean(...) with an !(...), it will never fire the error, otherwise it always will.
Here's a snippet, where it works at it should:
var mlptoday = {};
var timer = setTimeout(today,500);
function today(){
var d = new Date();
mlptoday.year = d.getFullYear(); //output: "2013"
mlptoday.month = checkTime(d.getMonth()+1); //output: "01"
mlptoday.date = checkTime(d.getDate()); //output: "27"
$('#values').html(JSON.stringify(mlptoday));
}
function checkTime(i) { if (i<10){i="0" + i} return i }
$(document).ready(function(){
$('form').submit(function(e){
e.preventDefault();
var remTime = $('input').val(); //user input
var remTimeArray = remTime.split('.') //output: ["2013","01","27"]
if (
!(remTimeArray[0] >= mlptoday.year &&
remTimeArray[1] >= mlptoday.month) ||
!((remTimeArray[1] == mlptoday.month) ? Boolean(remTimeArray[2]*1 >= mlptoday.date) : true)
){
$('#past').fadeIn('fast').delay(500).fadeOut('fast');
}
})
})
#past { display:none; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<form>
<input type="text" id="input" required autocomplete="off" placeholder="yyyy.mm.dd" pattern="^(19|20)\d\d[.](0[1-9]|1[012])[.](0[1-9]|[12][0-9]|3[01])$" required="" />
<button>Check</button>
</form>
<pre id="values"></pre>
<span id="past">the input date is in the past</span>
I need a better way to do this, and I don't want to use any date picker plugins.
I would compare the dates as integers to avoid complex logic.
var todayConcat = "" + parent.mlptoday.year + parent.mlptoday.month + parent.mlptoday.date;
var remTimeConcat = remTime.replace(/\./g, "");
if (remTimeConcat < todayConcat) {
//the input time is in the past
}
Just make sure the dates and months always have the leading zero.