How to add minutes to an hour in a datetime-local input? - javascript

I am copying the value of an input of type datetime-local (date_start) to another once the user writes in the first one (date_end). However I would like to be able to add 20 minutes more to the result in the second input (date_end) How could I do it?The format is example 10/20/2017 15:00
$("#date_start").keyup(function(){
var value = $(this).val();
$("#date_end").val(value);
});

The normal JQuery selector does not seem to work with this element, so I have used document.querySelector() instead of $(), So please find below my solution, this implements the stepUp() method of the DatetimeLocal object which will increment the value by minutes. Also please note I am adding the click event also in addition to keyup, since it seems necessary for this input element.
var start=document.querySelector('input[type="datetime-local"]#date_start'), end = document.querySelector('input[type="datetime-local"]#date_end')
start.value = start.value;
end.stepUp(20);
$("#date_start").on("click keyup", function(){
end.value = start.value;
end.stepUp(20);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="datetime-local" class="form-control" id="date_start" name="date_start" value="2017-06-01T08:30">
<input type="datetime-local" class="form-control" id="date_end" name="date_end" >
The Javascript equivalent for this will be.
var end = document.querySelector('input[type="datetime-local"]#date_end'), start = document.querySelector('input[type="datetime-local"]#date_start');
end.value = start.value;
end.stepUp(20);
start.addEventListener("click", addMinutes);
start.addEventListener("keyup", addMinutes);
var addMinutes = function(){
end.value = start.value;
end.stepUp(20);
};
<input type="datetime-local" class="form-control" id="date_start" name="date_start" value="2017-06-01T08:30">
<input type="datetime-local" class="form-control" id="date_end" name="date_end" >

try this
$( document ).ready(function() {
DateObj = Date.parse("10/20/2017 16:00");
// vale you get $("#date_end").val(value);
var date = new Date(DateObj+1200000);
console.log(date.toLocaleString('en-US',{ hour12: false }));
});
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>

Related

Javascript add year to date and put in html input

In a view, I have a date that the user must enter.
What I want is that the other dates are automatically filled in with +2 years for one and +5 years for another.
Thank you for your help.
html
<input type="date" th:field="*{date_fabrication}" class="form-control
col-xs-3 col" id="fabId"
th:onblur="majdates()"
th:errorclass="invalid"
th:placeholder="#{fabricationEquipment}"
style="width: 200px;font-size:12px;"
required>
function
<script>
function majdates() {
var recupDate = document.getElementById("fabId").value;
var plusTwoYears = recupDate.setFullYear(date.getFullYear() + 2);
document.getElementById("commissioningId").value = plusTwoYears;
}
</script>
edit : the target date :
<input type="date" th:field="*{date_mise_en_service}" class="form-control col"
id="commissioningId"
th:errorclass="invalid"
th:placeholder="#{commissioningEquipment}"
style="width: 200px;font-size:12px;">
thanks to Rory, the solution below
<script>
document.querySelector('#fabId').addEventListener('blur', e => {
var recupDate = new Date(e.target.value);
var plusTwoYears = new
Date(recupDate.setFullYear(recupDate.getFullYear() + 2));
var formatedPlusTowYears =plusTwoYears.toISOString().slice(0,10);
document.querySelector("#commissioningId").value = formatedPlusTowYears;
document.querySelector("#volumeId").value = formatedPlusTowYears;
});
</script>
Your code is almost there. The main issue is that recupDate will be a string. You need to parse it to a Date object in order to call setFullYear on it.
Also note that the result of setFullYear() will be an epoch timestamp, not a date, so you'll again need to parse the response of that to a Date object - and possibly format it manually depending on the output required.
document.querySelector('#fabId').addEventListener('blur', e => {
var recupDate = new Date(e.target.value);
var plusTwoYears = new Date(recupDate.setFullYear(recupDate.getFullYear() + 2));
document.querySelector("#commissioningId").value = plusTwoYears;
});
input {
width: 200px;
font-size: 12px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="date" class="form-control col-xs-3 col" id="fabId" required />
<input type="text" readonly id="commissioningId" />
Finally, I also changed the logic to use an unobtrusive event handler instead of the onblur attribute, as the latter are no longer good practice.

Javascript: which Dom event can be bound to Input type=date element?

I want to check if users are under the legal age for part time job based on their birthday. This is what I have done so far.
<script>
function ageCheck() {
var date=new Date();
var year=date.getFullYear();
var month=date.getMonth()+1;
var bday=document.getElementById("bday").value;
var bdayArr=bday.split("-");
var bYear=bdayArr[0];
var bMonth=bdayArr[1];
var bDay=bdayArr[2];
}
</script>
<span class="error">*</span>
<label for="bday">
<span class="register">Birthday</span></label>
<span id="ageInfo"></span>
<input type="date" name="bday" required="required" onblur="ageCheck()">
I make simple example with your html. You can see it here: https://stackblitz.com/edit/js-cg131i?embed=1&file=index.html
You can bind to 'input' event, as this is the standard event for either change or copy-paste event. You should change the input element like this,
<input type="date" name="bday" required="required" oninput="ageCheck(this.value)">
And Change your function to get the value in parameter.
function ageCheck(date) { console.log(date);}
If you want to use onblur, you can do it like that.
function ageCheck() {
var bdayString = birthday.value;
bdayString = bdayString.split("-")
var bdayNumber = [];
bdayString.map( val =>{
bdayNumber.push(parseInt(val))
})
var year = bdayNumber[0];
var month = bdayNumber[1];
var day = bdayNumber[2];
// if legal age is 18
legalAge = 18;
if( 2019 - year >= legalAge){
console.log( true);
}
}
<span class="error">*</span>
<label for="bday"><span class="register">Birthday</span></label> <span id="ageInfo"></span>
<input type="date" id="birthday" name="bday" required="required" onblur="ageCheck()" vamue="">

On keyup get each input values to php script

I'm trying to get each input value on keyup with comma separated. My code is working fine with onclick event but not with on keyup.
<input type="text" class="date" name="date[]" onkeyup="showHint(this.value)" />
This is part of my js function showhint where i'm defining the input value.
var DoB = [];
$(".date").each(function(){
DoB.push($(this).val());
});
var newDob = DoB.slice(0,-1);
xmlhttp.open("GET","validation.php?q="+newDob+",true);
Can anyone help me with this what is my mistake here?
Thanks in advance.
Are you sure the issue is the keyup? It seems to me the DoB.slice(0, -1) is causing your code not to work.
I replaced it with a DoB.join(','); to create the comma separated string.
function showHint(someValue) {
var DoB = [];
$(".date").each(function(){
//console.log($(this).val());
DoB.push($(this).val());
});
//var newDob = DoB.slice(0, -1);
var newDob = DoB.join(',');
document.getElementById("URL").value = "validation.php?q="+newDob;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="date" name="date[]" onkeyup="showHint(this.value)" />
<input type="text" class="date" name="date[]" onkeyup="showHint(this.value)" />
<br>URL : <input type="text" size="50" id="URL"/>
try this:
$( ".date" ).keyup(function() {
DoB.push($(this).val());
});
As per your code, you don't have to keep array DoB. as you have only one dob element. and you can directly get value of input.
following code will work for you
function showHint(){
var DoB = $(".date").val();
console.log(DoB);
xmlhttp.open("GET","validation.php?q="+DoB +",true);
}
I also had this happen to me before, when I used the onkeyup event in the script itself it works fine for me.
Here's an example:
document.getElementById("fname").onkeyup = function() {myFunction()};
function myFunction() {
var x = document.getElementById("fname");
x.value = x.value.toUpperCase();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<body>
<p>Press a key inside the text field and release it to set the text to uppercase.</p>
Enter your name: <input type="text" id="fname">
</body>
</html>

Display date as dd-mm-yyyy format for input type=date

I have my code :
<input type="date" class="form-control" id="training_date"
name="training_date" placeholder=" select" value=""
onfocus="(this.type='date')"
onfocusout="(this.type='date')" max=<?php echo date('Y-m-d'); ?>>
I need to display my date in following date-format dd-mm-yyyy format in the textbox.
What I would recommend is to make a array with the 12 months of the year (because the will never change)
_currentDate() {
var date = new Date();
for (var i = 0; this.months.length > i; i++) {
if (date.getMonth() === i) {
var displayMonth = this.months[i].month;
}
}
var displayDate = date.getDate() + ' ' + displayMonth + ' ' + date.getFullYear();
return displayDate;
}
Use the value that you return in your function you just need to insert where you want to display it so in your case your input
Hope this helps :)
Please note: <input type="date"> is not supported in IE and Firefox. Hence, it's not good idea to implement it in as it's against robust UI/UX design, and might invite later bugs.
You should use jquery's datepicker, moment.js or combination of both to achieve your requirement.
To close the question and provide what can be done and tested. Here is implementation.
In this example:
I am assigning today's date to <input type="date"> by forming a date string in yyyy-mm-dd format and setting attribute value
whenever I am changing the the date in #datepicker, I am forming a date string in dd-mm-yyyy format and providing it as value to #textbox
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var d = new Date();
function twoDigitDate(d){
return ((d.getDate()).toString().length == 1) ? "0"+(d.getDate()).toString() : (d.getDate()).toString();
};
function twoDigitMonth(d){
return ((d.getMonth()+1).toString().length == 1) ? "0"+(d.getMonth()+1).toString() : (d.getMonth()+1).toString();
};
var today_ISO_date = d.getFullYear()+"-"+twoDigitMonth(d)+"-"+twoDigitDate(d); // in yyyy-mm-dd format
document.getElementById('datepicker').setAttribute("value", today_ISO_date);
var dd_mm_yyyy;
$("#datepicker").change( function(){
changedDate = $(this).val(); //in yyyy-mm-dd format obtained from datepicker
var date = new Date(changedDate);
dd_mm_yyyy = twoDigitDate(date)+"-"+twoDigitMonth(date)+"-"+date.getFullYear(); // in dd-mm-yyyy format
$('#textbox').val(dd_mm_yyyy);
//console.log($(this).val());
//console.log("Date picker clicked");
});
});
</script>
</head>
<body>
<div style="width: 50%;height:50px; float:left;">
Enter your Birthday!!:<br>
<input id="datepicker" type="date" name="bday" style="margin-bottom: 200px;"></br><br>
</div>
<div style="width: 50%;height:50px; float:right;">
Date chosen(dd-mm-yyyy):<br>
<input id="textbox" type="text" value="dd-mm-yyyy"></input>
</div>
</br></br></br></br></br></br>
<p><strong>Note:</strong> type="date" is not supported in Firefox, or Internet Explorer 11 and earlier versions.</p>
</body>
</html>
You can use the below code to achieve this.
<input type="date" class="form-control" id="training_date" name="training_date" placeholder=" select" value="" onfocus="(this.type='date')" onfocusout="(this.type='date')" pattern="\d{1,2}/\d{1,2}/\d{4}" >

HTML Form Submit to Google Calendar: Uncaught TypeError, Failed due to illegal value in property: 1

I believe I'm having a similar issue to this problem, but his solution isn't working for me.
I'm trying to have a Google App Script serve an HTML form that adds a Google Calendar event to my calendar.
Code.gs:
function doGet() {
return HtmlService.createHtmlOutputFromFile('form.html')
.setSandboxMode(HtmlService.SandboxMode.IFRAME);
}
function scheduleEvent(array) {
CalendarApp.getDefaultCalendar().createEvent(array[0], array[1], array[2]);
return 1;
}
form.html
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<link href="//netdna.bootstrapcdn.com/bootswatch/3.3.6/paper/bootstrap.min.css" rel="stylesheet">
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="//netdna.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.13.0/moment.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.4/moment-timezone-with-data-2010-2020.min.js"></script>
<style>body{padding:8px}</style>
</head>
<body>
<form class="form">
<fieldset>
<legend>Schedule a Meeting</legend>
<div class="form-group">
<label for="email">Your email:</label>
<input type="email" class="form-control" id="email" placeholder="you#gmail.com" required>
</div>
<div class="form-group">
<label for="eventName">What's the topic?</label>
<input type="text" class="form-control" id="eventName" required>
</div>
<div class="form-group">
<label for="eventLocation">Where?</label>
<input type="text" class="form-control" id="eventLocation" required>
</div>
<div class="form-group">
<label for="startTime">When? (EST)</label>
<input type="datetime-local" class="form-control" id="startTime" required>
</div>
<div class="form-group">
<label for="select">How Long?</label>
<select class="form-control" id="duration" required>
<option value="15">15 Minute Meeting</option>
<option value="30" selected>30 Minute Meeting</option>
<option value="60">60 Minute Meeting</option>
</select>
</div>
<button type="submit" class="btn btn-primary submit" onClick="preprocessForm(this.form)">Submit</button>
</fieldset>
</form>
<script type="text/javascript">
function preprocessForm (form) {
// check if they filled out their email, and set the variable if they did
if (form.email.value) {
var email = form.email.value;
} else {
alert("Please enter your email address, so I know who the appointment is with!");
event.preventDefault();
return 1;
}
// check if they filled out the event name, and set the variable if they did
if (form.eventName.value) {
var eventName = form.eventName.value;
} else {
alert("Please enter a name for the event!");
event.preventDefault();
return 1;
}
// set and format the event time and date, and grab the current time and date
var currentTime = moment().tz('America/New_York');
var startTime = moment(form.startTime.value).tz('America/New_York');
var formattedStartTime = startTime.toDate();
// html5 should stop the user from skipping filling out this section, but check anyway, just in case
if (!form.startTime.value) {
alert("Please enter a time for the event to occur!");
event.preventDefault();
return 1;
}
// we don't want people scheduling meetings in the past
if (startTime.isBefore(currentTime)) {
alert("Please pick a time that is in the future!");
console.log('Start Time: ' + startTime);
console.log('Current Time: ' + currentTime);
event.preventDefault();
return 1;
}
// check if they filled out the event location, and set the variable if they did
if (form.eventLocation.value) {
var eventLocation = form.eventLocation.value;
} else {
alert("Please enter an event location, so I know where to go!");
event.preventDefault();
return 1;
}
// it's not possible to skip the duration, since it's a dropdown that defaults to 30 minutes
var duration = form.duration.value;
var endTime = moment(startTime).add(duration, 'minutes');
var formattedEndTime = endTime.toDate();
var assembledDetails = [eventName, formattedStartTime, formattedEndTime];
//toadd: , {location: eventLocation, guests: email}
google.script.run.scheduleEvent(assembledDetails);
// things to try and stop the redirect/refresh when pressing the submit button
event.preventDefault();
return false;
}
</script>
</body>
</html>
I'm not having any luck. On submit, I get this error in the console:
Any advice?
Thanks!
You can't send a date object in the array. Property 1 is the second element in the array: assembledDetails
var assembledDetails = [eventName, formattedStartTime, formattedEndTime];
You could change the code to this:
formattedStartTime = formattedStartTime.toDateString();
formattedEndTime = formattedEndTime.toDateString();
var assembledDetails = [eventName, formattedStartTime, formattedEndTime];
Then you'd need to convert the date strings back to date objects in the server code.
Or:
You can strigify the object:
assembledDetails = JSON.stringify(assembledDetails);
google.script.run.scheduleEvent(assembledDetails);
And convert the object back in the server:
function scheduleEvent(array) {
array = JSON.parse(array);
Quote from documentation:
Requests fail if you attempt to pass a Date, Function, DOM element besides a form, or other prohibited type, including prohibited types inside objects or arrays.
Apps Script documentation - Parameters and return values

Categories

Resources