Cant get onChange to trigger in Javascript using Datepicker - javascript

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)
}
})

Related

How to prevent user to enter wrong date into to input

`I am working on a date time input inside a web app. The format for date and time is MM/DD/YYYY HH:MM:SS. I have to validate the month, date and year. For example, it should prevent user from entering 13 instead of 12 in the month placeholder.
Below is html code.
<label>Date time:
<input placeholder="__/__/____ __:__:__" data-slots="_">
</label><br>
and the js
<script>
document.addEventListener('DOMContentLoaded', () => {
for (const el of document.querySelectorAll("[placeholder][data-slots]")) {
const pattern = el.getAttribute("placeholder"),
slots = new Set(el.dataset.slots || "_"),
prev = (j => Array.from(pattern, (c, i) => slots.has(c) ? j = i + 1 : j))(0),
first = [...pattern].findIndex(c => slots.has(c)),
accept = new RegExp(el.dataset.accept || "\\d", "g"),
clean = (input) => {
input = input.match(accept) || [];
return Array.from(pattern, c =>
input[0] === c || slots.has(c) ? input.shift() || c : c
);
},
format = () => {
const [i, j] = [el.selectionStart, el.selectionEnd].map(i => {
i = clean(el.value.slice(0, i)).findIndex(c => slots.has(c));
return i < 0 ? prev[prev.length - 1] : back ? prev[i - 1] || first : i;
});
el.value = clean(el.value).join``;
el.setSelectionRange(i, j);
back = false;
};
let back = false;
el.addEventListener("keydown", (e) => back = e.key === "Backspace");
el.addEventListener("input", format);
el.addEventListener("focus", format);
el.addEventListener("blur", () => el.value === pattern && (el.value = ""));
}
});
</script>
Even if its in jquery, its fine but please no External libraries or plugins.
I have tried to prevent it using prevent.default() for keypress event but have reached nowhere.
I just want the user to be prevented from entering wrong date instead of validating after entered.`
You can do this
<input type="datetime-local" required id="date" name="date">
Not sure you wanted this, but you can consider using the datepicker (jQuery + datepicker.js).
add tags:
<script type="text/javascript" src="../Scripts/jQuery/jquery.min.js"></script>
<script type="text/javascript" src="../Scripts/jQuery/bootstrap-datepicker.js"></script>
<link rel="stylesheet" href="../CSS/bootstrap-datepicker.css" type="text/css">
Html:
<input id="myDate" name="myDate" type="text" class="form-control date-input" placeholder="DD MM YYYY HH:MM:SS" readonly />
jQuery:
$(function () {
$('#myDate').datepicker({
//format of your date displayed
format: "M/d/yyyy h: mm tt"
}).on('changeDate', function (e) {
//some code here
});
Sorry if it's not what you were looking for

Condition on Jquery Validate

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>

How to load datetimepicker with different date-range for multiple inputs

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}
}
});
}
});

Date range for table Javascript

I currently have this filter on my table
(function(document) {
'use strict';
var LightTableFilter = (function(Arr) {
var _input;
function _onInputEvent(e) {
_input = e.target;
var tables = document.getElementsByClassName(_input.getAttribute('data-table'));
Arr.forEach.call(tables, function(table) {
Arr.forEach.call(table.tBodies, function(tbody) {
Arr.forEach.call(tbody.rows, _filter);
});
});
}
function _filter(row) {
var text = row.textContent.toLowerCase(), val = _input.value.toLowerCase();
row.style.display = text.indexOf(val) === -1 ? 'none' : 'table-row';
}
return {
init: function() {
var inputs = document.getElementsByClassName('light-table-filter');
Arr.forEach.call(inputs, function(input) {
input.oninput = _onInputEvent;
});
}
};
})(Array.prototype);
document.addEventListener('readystatechange', function() {
if (document.readyState === 'complete') {
LightTableFilter.init();
}
});
})(document);
I'm wondering how i can use two date fields with this to act as a date range? i have just tried adding two date fields in but that just gives me the response of two exact dates, not the range in between
Heres my html code for the dates
<label for="Date">Date From:</label>
<input type="date" id="datefrom" class="light-table-filter form-control" style="width:50%" data-table="order-table" placeholder="Filter">
<label for="Date">Date to:</label>
<input type="date" id="dateto" class="light-table-filter form-control" style="width:50%" data-table="order-table" placeholder="Filter">
I think this will need some expanding of you filter function, but you can compare dates with compare operators like >= and <=.
So you need to create dates of your 2 input fields and a date of the table row value. You need to identify the cell if it is indeed the date cell, otherwise it will create date objects of arbitrary cell values. I don't know your full HTML, but this can be done by adding a class, for example (see my code).
For example:
function _filter(row) {
var dateFrom = new Date(document.getElementById('datefrom').value);
var dateTo = new Date(document.getElementById('dateto').value);
dateFrom.setHours(0);
dateTo.setHours(0);
var text = row.textContent.toLowerCase(),
val = _input.value.toLowerCase();
row.style.display = text.indexOf(val) === -1 ? 'none' : 'table-row';
if (!isNaN(dateFrom.getTime()) && !isNaN(dateTo.getTime())) {
var cell = row.querySelectorAll(".date")[0];
var arr = cell.innerText.split('-');
var rowDate = new Date(arr[0],parseInt(arr[1])-1,arr[2]);
if (!isNaN(rowDate.getTime())) {
if (rowDate >= dateFrom && rowDate <= dateTo) {
row.style.display = 'table-row';
} else {
row.style.display = 'none';
}
}
}
}
Make sure the Date constructor receives valid parsable date formats. See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date for more info.
EDIT
Updated answer and corrected time.

Logic to use to find out if the entered date is today or later

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.

Categories