How to set calendar date from javascript - javascript

when user enters ddMMyy or ddMMyyyy.I want to convert it into dd/MM/yyyy format. To achieve this i
have written a javascript. It works fine but when i focus on textbox again it doesnt show selected date
as javascript converted date(i.e it doesnt fire event when i manually change the date of the textbox).
How to make calendar control to select the date after calling "ConvertToDate" function?
<script type="text/javascript">
function ConvertToDate(txtCnt) {
try {
txtVal = txtCnt.value;
var dd = txtVal.charAt(0).toString() + txtVal.charAt(1).toString();
var MM = txtVal.charAt(2).toString() + txtVal.charAt(3).toString();
var year = txtVal.substring(4);
if (year.length == 2) year = "20" + year;
var jsDate = new Date();
txtCnt.value = dd + "/" + MM + "/" + year;
} catch (e) {
}
return false;
}
</script>
<asp:TextBox ID="txtFromDt" runat="server" onblur="return ConvertToDate(this)" Width="80px"></asp:TextBox>
<cc1:CalendarExtender ID="txtFromDt_CalendarExtender" runat="server" CssClass="cal_Theme1"
Format="dd/MM/yyyy" Enabled="True" TargetControlID="txtFromDt" />

As you can call this function on :-- onblur event as it fire
when an object loses focus.

Related

Select a date 7 days after current date in javascript

I have input in html like this:
<input class="form-control" placeholder="Date of Collection *" id="m_date" name="m_date" type="date" tabindex="6" required/>
I would like to select a date that is more than 7 days from the current date, if I select a date before 7 days from current, it should prompt saying "Wrong date selected"
How do I do that in javascript?
I tried the following:
var date = new Date();
date.setDate(date.getDate() + 7);
console.log(date);
It gives the date correctly. How do I use this to compare if date is 7 after or not and prompt accordingly?
Thanks!
UPDATE:
<html>
<body>
<input class="form-control" placeholder="Date of Collection *" id="m_date" name="m_date" type="date" tabindex="6" required/>
</body>
</html>
<script>
let cal = document.body.getElementsByClassName('form-control')[0];
cal.onchange = function(e)
{
var selectDate = e.target.value
var startDate = new Date(Date.parse(selectDate));
console.log(startDate);
var dateAfter7Days = new Date(new Date().getTime()+(7*24*60*60*1000))
console.log("7 days " + dateAfter7Days);
if (startDate => dateAfter7Days )
{
console.log("Allow");
}
else
{
console.log("Don't allow");
}
}
</script>
I am getting "Allow" for any date I select.
The point is comparing two date values. If current date - selected date > 7 then it should print prompt. The problem is how to get selected date.
You can get the selected date from the input tag by event value. On changed date, the value get logged.
let cal = document.body.getElementsByClassName('form-control')[0];
cal.onchange = function(e) {
console.log(e.target.value);
}
<input class="form-control" placeholder="Date of Collection *" id="m_date" name="m_date" type="date" tabindex="6" required/>
var date = new Date();
var next_seven_date = d.getDate()+7;
var current_month = d.getMonth();
current_month++; // month start from 0 then we need to +1
var current_year = d.getFullYear();
var weekDate =(next_seven_date + "/" + current_month + "/" + current_year);
date.setDate(weekDate);
Since your problem is to compare dates not creating them I have updated my answer which might hlp you
var currentDate= new Date();
currentDate= new Date(currentDate.getFullYear(),currentDate.getMonth(),currentDate.getDate(),0,0,0)
var idealDifference= (7*24*60*60*1000);
//In your case this date might comes from some date selection user control. Be aware to make the time part of each date to same
var userSelectedDate = new Date(2021, 04, 04,currentDate.getHours(),0,0,0)
if((userSelectedDate.getTime()-currentDate.getTime())>=idealDifference)
{
console.log(userSelectedDate, ' is after 7 days from ',currentDate)
}
else
{
console.log(userSelectedDate, ' is before 7 days from ',currentDate)
}
Note: It is important to unset the time part of both the dates before comparing for this logic to work

Add one hour to string on client side

I have two timepicker in my view
#Html.Kendo().TimePickerFor(m=>m.AttendeeStartTime).Format("HH:mm")
#Html.Kendo().TimePickerFor(m=>m.AttendeeEndTime).Format("HH:mm")
This is how it looks
and here is rendered HTML for From Timepicker,
<input data-val="true" data-val-required="The AttendeeStartTime field is required."
id="AttendeeStartTime" name="AttendeeStartTime" type="text" value="09:00" data-role="timepicker"
class="k-input valid" role="textbox" aria-haspopup="true" aria-expanded="false" aria-
owns="AttendeeStartTime_timeview" aria-disabled="false" aria-readonly="false" style="width: 100%;">
Whenever there is change in From timepicker, how can I add one hour to its value and set to to To timepicker?
This is what I have done,
$('##Html.IdFor(m=>m.AttendeeStartTime)').on('change', function () {
//var date = new Date();
endTime.value($(this).val());
alert(endTime.value());
This only sets the To value to the same as From when there is change, but I want to add an hour or some timespan to it.
How should i do that?
Use this:
$('##Html.IdFor(m=>m.AttendeeStartTime)').on('change', function () {
//try getting the date from the date picker
var date = $("##Html.IdFor(m=>m.AttendeeStartTime)").data("kendoTimePicker").value();
if (date) {
//convert the string to a date
date = new Date(date); //you can probably skip this step since the Kendo DatePicker returns a Date object
//increase the "hours"
date.setHours(date.getHours() + 1);
//set it back in the "to" date picker
$("##Html.IdFor(m=>m.AttendeeEndTime)").data("kendoTimePicker").value(date);
//alert(endTime.value());
}
}
You can write a custom function like this,
function addMinutes(time, minsToAdd) {
function z(n){ return (n<10? '0':'') + n;};
var bits = time.split(':');
var mins = bits[0]*60 + +bits[1] + +minsToAdd;
return z(mins%(24*60)/60 | 0) + ':' + z(mins%60);
}
addMinutes('05:40', '20'); // '06:00'
addMinutes('23:50', 20);
Your scenario should be,
$('##Html.IdFor(m=>m.AttendeeStartTime)').on('change', function () {
//var date = new Date();
endTime.value($(this).val());
addMinutes($(this).val(), '60');
alert(endTime.value());

How to pass datepicker change event

I'm checking a date entered with a datepicker control in jquery from an Html.TextBoxFor helper:
<%=Html.TextBoxFor(c => Model.mydate, new { #class = "datepicker", maxlength = 10, #onBlur = "chkDate"})%>
The datepicker mask for the textbox appears to be MM/DD/YYYY . So, my script checks for an underscore and displays an error. This works if the user igonores the datepicker and tries to enter a date freehand but not if the datepicker is used. When a date is chosen, the value passed to my script is still underscores and no value. Here's my script:
<script type="text/javascript">
$(document).on("blur", "input[name=mydate]",
function chkDate() {
var len = $("input[name=mydate]").val().length;
var date = $("input[name=mydate]").val();
var month = date.slice(0, 2);
var day = date.slice(3, 5);
var year = date.slice(6, 10);
alert("chkBirthday " + month);
if (month == '__') {
document.getElementById("MainContent_ErrorMessage").visibility = 'visible';
document.getElementById("MainContent_ErrorMessage").innerHTML = 'No date has been entered. Please enter a date';
}
});
There's an event onChange associated with datepicker. Is this what I should be using? If so, how do I specify that in my helper and what script changes do I need to make?
Try this,
$(document).on("change", "input[name=mydate]",function (){
var len = $(this).val().length;
var date = $(this).val();
var month = date.slice(0, 2);
var day = date.slice(3, 5);
var year = date.slice(6, 10);
alert("chkBirthday " + month);
if (month == '__') {
document.getElementById("MainContent_ErrorMessage").visibility = 'visible';
document.getElementById("MainContent_ErrorMessage").innerHTML = 'No date has been entered. Please enter a date';
}
});
Assuming you are using the popular JQuery UI's Datepicker, weirdly enough they are not entitled events but callbacks that can handle this event. See onSelect or onClose.

Validation with KendoUI datetime

Hi i have an app where user can select for start datetime and end datetime if they want to create an event.
Now this is an html where i use KendoUI datetime plugin:
<div class="demo-section" style="width: 535px;">
<label for="start">Start date:</label>
<input id="start" value="01/01/2013" />
<label for="end" style="margin-left:3em">End date:</label>
<input id="end" value="01/01/2013"/>
</div>
</li>
<script type="text/javascript">
$(document).ready(function(){
function startChange() {
var startDate = start.value();
if (startDate) {
startDate = new Date(startDate);
startDate.setDate(startDate.getDate());
end.min(startDate);
}
}
function endChange() {
var endDate = end.value();
if (endDate) {
endDate = new Date(endDate);
endDate.setDate(endDate.getDate());
start.max(endDate);
}
}
var start = $("#start").kendoDateTimePicker({
change: startChange,
parseFormats: ["MM/dd/yyyy"]
}).data("kendoDateTimePicker");
var end = $("#end").kendoDateTimePicker({
change: endChange,
parseFormats: ["MM/dd/yyyy"]
}).data("kendoDateTimePicker");
start.max(end.value());
end.min(start.value());
});
Issues is i cant get validation as i want. Suppose user select From date the To date should display date which is greater that currently selected From date.My currrent code seems not works well. Thanks
Are you saying that you want to be able to select a From date greater than To, and that when you do To should automatically update to be greater than From?
If so you're almost there. You just need to update the startChange function to update the To date relative to From.
function startChange() {
var startDate = start.value();
if (startDate) {
startDate = new Date(startDate);
startDate.setDate(startDate.getDate());
end.min(startDate);
var endDate = end.value();
if (endDate && endDate <= startDate) {
endDate.setDate(startDate.getDate() + 1);
end.value(endDate);
}
}
}
Check this jsFiddle for a full working example.

javascript add number of input fields equal to the number of months

I have two input fields with date1 and date2.Below this two fields i need a button that when i press it, will create a number of input fields equal to the number of months between the 2 date fields.
For example i have date1=2012-03-21 and dat2=2012-06-21. It should generate 3 input fields
Can you help me with this one?
Let's assume the HTML looks something like this:
<div id="dateRange">
<input type="text" id="startDate">
<input type="text" id="endDate">
</div>
<div id="monthlyEntries"/>
Now, a month is not a uniform number of days ("30 days has September, April, June,and November..."), so I'm guessing the day portion of the dates don't matter.
Then, the javascript to call on change (or clicking a button, or whatever), would look something like this:
function buildMonthlyEntries() {
var startDate = new Date(document.getElementById('startDate').value);
var endDate = new Date(document.getElementById('endDate').value);
if(startDate == "Invalid Date" || endDate == "Invalid Date") { return null; }
var entryCount = (endDate.getMonth() + endDate.getFullYear()*12) - (startDate.getMonth() + startDate.getFullYear()*12);
var monthlyEntries = document.getElementById('monthlyEntries');
monthlyEntries.innerHTML = "";
for(var i = 0; i < entryCount; i++) {
var textElement = document.createElement('input');
textElement.setAttribute('type', 'text');
textElement.setAttribute('id', 'entry' + i);
monthlyEntries.appendChild(textElement);
}
return null;
}
You can run a loop based upon the difference in the dates. In pseudo code it would be something like
var difference = month2 - month1;
for(x=0;x<difference,x++){
add inputfield;
}

Categories