Subtract 1 day from date input box and submit using button - javascript

I'm trying to collect 2 dates using input boxes ids From and To. I would like to subtract 1 day from the date value received using "FROM" text box and pass that new value to the button click event.
The code below works to push values received from the input box. However, i wish to subtract 1 day and pass on the same.
<script src="https://code.jquery.com/jquery-3.4.1.min.js" type="text/javascript"></script>
From : <input type="date" class="form-control" id="From" placeholder="From" aria-label="From">
To : <input type="date" class="form-control" id="To" placeholder="To" aria-label="To">
<input type="button" onclick="location.href='#SITE#/TDL-Test-code.aspx?FromTo=(Date ge datetime%27'+FD+'T00:00:00.000Z%27) and (Date le datetime%27'+ document.getElementById('To').value+'T23:59:00.000Z%27)';" value="Submit" />
Edit:
Following is my moment JS function
var oldfrom = document.getElementById('From').value;
newdate = moment(oldfrom).subtract(1, 'days').format("YYYY-MM-DD");
var FD = newdate;

Issue was fixed with solution below.
document.getElementById("From_Local").oninput = function() {
var dateLocal = document.getElementById("From_Local").value;
var dateUTC = moment.utc(dateLocal).subtract(4, 'hours').format("YYYY-MM-DD");
document.getElementById("From_UTC").value = dateUTC;
}
From:<input name="From" required type="date" id="From_Local">
<input type="hidden" id="From_UTC">
To:<input name="To" required type="date" id="To">
<input type="button" onclick="location.href='SITE_URL?FromTo=(Date%20ge%20datetime%27'+ document.getElementById('From_UTC').value+'T00:00:00.000Z%27)%20and%20(Date%20le%20datetime%27'+ document.getElementById('To').value+'T00:00:00.000Z%27)';" value="Submit" />

Related

Insert time into a field only when selected and then click

The time only inserts on the first field https://jsfiddle.net/cjy28u1o/. I want to insert the time based on the field that is selected.
$('#time').click(function(){
var time = new Date();
$('#time-holder').val(time.toTimeString());
});
You can store the focused element using .focusin() in a variable and then set it's value when click. Also using the attribute class instead of id is more meaningful in this case:
$(function(){
var $focused;
$('.time-holder').focusin(function(){
$focused = $(this);
});
$('#time').click(function(){
var time = new Date();
if($focused != undefined)
$focused.val(time.toTimeString());
else
alert('Not focused any element');
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" value="" class="time-holder">
<input type="text" value="" class="time-holder">
<input type="text" value="" class="time-holder">
<input type="button" value="time" name="timer" id="time">
In HTML DOM, id is unique.
If you put same id for multiple elements, DOM and jQuery will fire event on first matched element with the specified id.
Rest of the elements will be simply ignored.
You need to add class to all elements as multiple elements can have same class.
This way, you will get time for all text fields.
So, your code corrected now:
<input type="text" value="" id="time-holder" class="time-text">
<input type="text" value="" id="time-holder2" class="time-text">
<input type="text" value="" id="time-holder3" class="time-text">
<input type="button" value="time" name="timer" id="time">
And Javascript:
$(function(){
$('#time').click(function(){
var time = new Date();
$('.time-text').val(time.toTimeString());
});
}
);
Try
$(
function(){
let lastFocusEl=null;
$('#time').click(function(){
var time = new Date();
if(lastFocusEl) lastFocusEl.value = time.toTimeString();
});
let f = function() { lastFocusEl=this};
$('#time-holder').focus(f);
$('#time-holder2').focus(f);
$('#time-holder3').focus(f);
}
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" value="" id="time-holder">
<input type="text" value="" id="time-holder2">
<input type="text" value="" id="time-holder3">
<input type="button" value="time" name="timer" id="time">
the time is only insert on first field
It is happening because, You have given the diffrent IDs to all the three elements.You are only targeting the first element. You should use class instead. Try this,
<input type="text" value="" class="time-holder"> <input type="text" value="" class="time-holder"> <input type="text" value="" class="time-holder">
<input type="button" value="time" name="timer" id="time">
JS CODE:
$(
function(){
$('#time').click(function(){
var time = new Date();
$('.time-holder').val(time.toTimeString());
});
}
);
I would listen to the focus event, and then set the time to the last focused element.
$('input[type="text"]').focus(function(){
this.dataset.selected = true;
});
$('#time').click(function(){
var time = new Date();
var selectInput = $('[data-selected="true"]');
selectInput.val(time.toTimeString());
});

How to get the timestamp of data input in an HTML form

I have form like below:
<div id="form">
<form>
First Name: <input type="text" name="firstname" id="firstname">
Last Name: <input type="text" name="lastname">
Start Time: <input type="hidden" name="starttime" id="starttime">
<input type="submit" value="Submit">
</form>
</div>
I want to store a timestamp in a local storage when data is entered for the first time in firstname input. When the form is submitted, I will insert that timestamp as Start Time and form submit time as End Time in database.
Here is what I have so far:
<script>
$(document).ready(function(){
var startTime = '';
$('#firstname').change(function (){
if (startTime) == ''
{
var timeStamp = new Date();
sessionStorage.setItem("startTime",timeStamp);
}
});
});
</script>
Now, how do I send the startTime value from javascript to the starttime html input? Any help will be much appreciated.
You can use step attribute in your input tag:
<input type="time" name="timestamp" step="1">
W3C: input: type=time

extract year from date and calculate datedifference

I am relative new in coding and recently i have to do some date manipulations with data entered in a form. I searched a lot and I haven't found the solution that works for me.
Here is the issue:
The user enters following data in datetime-local fields in HTML:
1) Year of entering College (date 1)
2) Year of graduation (date 2)
3) Birthday (date 3)
I need a JQuery or a JavaScript script that uses this dates and output following:
1) Year of admitting, based on the admittion date (I know there is a getFullYear function, but I couldn't use it right...) >>> result1
2) Age at graduation (date difference between Birthdate and date of Graduation. >>> result2
I tried with adding datepicker but somehow I got really awful looking calendar which was displayed over the boxes. I couldn't install datetimepicker...
Thank you in advance. Your help is appreciated.
Here is my HTML code.
<input id="date1" type="datetime-local"/>
<label for="date1">admittion in Colleage</label>
<br />
<input id="result1" type="text" readonly="true" name="year" placeholder="=(getFullYear from date1)"/>
<label for="result1">year</label>
<br />
<input id="date2" type="datetime-local" />
<label for="date2">graduation</label>
<br />
<input id="date3" type="date" name="born" />
<label for="date3">born</label>
<br />
<input id="result2" type=“text” name="age" readonly="true" placeholder="=DATEDIF(Date3, Date2, Year)"/></textarea>
<label for="result2">age</label>
<br />
You didn't include the js code which is more important for this question. I'll include a couple functions that should help.
To find a year from a date, I use the following function
function getYearFromDate(date){
const yearFromDate = new Date();
yearFromDate.setTime(date.getTime());
yearFromDate.setFullYear(date.getFullYear() + 1);
return yearFromDate;
}
console.log(getYearFromDate(new Date()));
And the graduation age copied mostly from Calculate age given the birth date in the format YYYYMMDD
function getYearsBetween(oldDate, newDate) {
var age = newDate.getFullYear() - oldDate.getFullYear();
var m = newDate.getMonth() - oldDate.getMonth();
if (m < 0 || (m === 0 && newDate.getDate() < oldDate.getDate())) {
age--;
}
return age;
}
Including moment.js is also an option, but it's a large library I like to avoid if I can.
EDIT I thought you wanted year + 1 day. Getting the full year from the date is even easier.
const date = new Date();
console.log(date.getFullYear());
Edit: All together now
function updateGradYear(event) {
console.log(event.target.value);
let date = new Date(event.target.value);
document.querySelector('#result1').value = date.getFullYear();
}
function updateAge() {
let gradDate = new Date(document.querySelector('#date2').value);
console.log(document.querySelector('#date3').value);
let birthdate = new Date(document.querySelector('#date3').value);
document.querySelector('#result2').value = gradDate.getFullYear() - birthdate.getFullYear();
}
// set some default values
let today = new Date();
document.querySelector('#date1').value = today.toISOString().split('.')[0];
document.querySelector('#result1').value = today.getFullYear();
document.querySelector('#date2').value = today.toISOString().split('.')[0];
let birthdate = new Date(today.getTime);
birthdate.setFullYear(1984);
console.log(birthdate.toISOString().slice(0, 10).replace(/\//g, "-"));
document.querySelector('#date3').value = birthdate.toISOString().slice(0, 10).replace(/\//g, "-");
updateAge();
<input id="date1" type="datetime-local" onchange="updateGradYear(event)" />
<label for="date1">admittion in Colleage</label>
<br />
<input id="result1" type="number" readonly="true" name="year" placeholder="=(getFullYear from date1)" />
<label for="result1">year</label>
<br />
<input id="date2" type="datetime-local" onchange="updateAge()" />
<label for="date2">graduation</label>
<br />
<input id="date3" type="date" name="born" onchange="updateAge()" />
<label for="date3">born</label>
<br />
<input id="result2" type=“text” name="age" readonly="true" placeholder="=DATEDIF(Date3, Date2, Year)" /></textarea>
<label for="result2">age</label>
<br />
Let me know how this works for you! And as i said please enter all the fields while running this code!
$('#date1, #date2').on('blur',function(){
var dc = document.querySelector('input[id="date1"]');
var date = new Date(dc.value);
var collegeadmission = date.getFullYear();
$('#result1').val(date.getFullYear());
dc = document.querySelector('input[id="date2"]');
date = new Date(dc.value);
var collegegrad = date.getFullYear();
if(! isNaN(collegegrad))
$('#result2').val(collegegrad - collegeadmission);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="date1" type="datetime-local"/>
<label for="date1">admittion in Colleage</label>
<br />
<input id="result1" type="text" readonly="true" name="year" placeholder="=(getFullYear from date1)"/>
<label for="result1">year</label>
<br />
<input id="date2" type="datetime-local" />
<label for="date2">graduation</label>
<br />
<input id="date3" type="date" name="born" />
<label for="date3">born</label>
<br />
<input id="result2" type=“text” name="age" readonly="true" placeholder="=DATEDIF(Date3, Date2, Year)"/></textarea>
<label for="result2">age</label>
<br />
check out this url:http://jsbin.com/vebiwogipu/edit?html,js,output
Make sure u fill all the dates and time properly as you discussed in your html.
Similarly you can attach the output on click or change event.
and aso you can leverage getMonth() and getDay() in the code to get desired output.
Take a look at the label and may be alert, when you click the button, it shows year out of your first date field. As i said you need to add the logic for rest.
let me know if it makes sense, if not please add more information to make me understand!

Datetimepicker did not work on element that append form javascript

I have one input date, this input append from js like this
var inputdate = '<input type="text" name="date[]" class="form-control date" placeholder="Input date"';
$("form").append(inputdate);
And the html code is like this :
<form method="POST">
...
</form>
Initialize datetimepicker
$('.date').datetimepicker({
format: 'YYYY-MM-DD'
});
The input element append succesfully and the other form that have input date work with datetimepicker.
But the element that append from js is not showing datetimepicker, is there any mistakes?
I think you missed one thing here.
var inputdate = '<input type="text" name="date[]" class="form-control date" placeholder="Input date"';
It should have > at the end of string.
The initialization code should be Reexecuted after we append inputDate into $('form').
So the code should be:
var inputdate = '<input type="text" name="date[]" class="form-control date" placeholder="Input date">';
$("form").append(inputdate);
$('.date').datetimepicker({format: 'YYYY-MM-DD'});

JavaScript/Jquery Auto Generate Employee Id based on user input

I'm generating the empId using Servlet but my boss wants that when the user is typing, he will see the empId instantly based on what he inputs. And I'm not really familiar with JavaScript or JQuery, but I think it's the right tool to do this. Please help?
empId contains the first character in the first name, middle name, and surname plus a dash and the date of birth. Sample would be JHD-01011990.
Here's a simplified version of my HTML form:
<form method="post" action="../profile/SaveProfile">
<label for="empId">Employee ID</label>
<input id="empId" name="empId" type="text" placeholder="FML-MMDDYYYY" required readonly>
<label for="title">Title</label>
<select id="title" name="title">
<option value="0"></option>
<option value="1">Attorney</option>
<option value="2">Doctor</option>
<option value="3">Professor</option>
<option value="4">Engineer</option>
</select>
<label for="fname">Name</label>
<input id="fname" name="fname" type="text" placeholder="* First Name" required>
<input id="mname" name="mname" type="text" placeholder="* Middle Name" required>
<input id="lname" name="lname" type="text" placeholder="* Surname" required>
<input id="ename" name="ename" type="text" placeholder="Ext">
<label for="dob">* Date of Birth</label>
<input id="dob" name="dob" type="text" required>
<label for="doa">Date of Original Appointment</label>
<input id="doa" name="doa" type="text">
<button type="button">Close</button>
<button type="submit">Save</button>
</form>
And if needed, here's also my Java code for generating the empId
public String generateEmployeeId(String dateOfBirth, String firstName, String middleName, String surname) {
String[] birthdate = dateOfBirth.split("-");
String empId = firstName.charAt(0) + middleName.charAt(0) + surname.charAt(0);
empId += "-" + birthdate[1] + birthdate[2] + birthdate[0];
return empId;
}
I'd like to post a sample screen shot of my form but I can't. Please tell me if you need it.
Thank you!
Here's the jQuery code:
$(function() {
$("#fname,#mname,#lname,#dob").keyup(function() {
var birthdate = $("#dob").val().split('-');
var fname = $("#fname").val();
var lname = $("#lname").val();
var mname = $("#mname").val();
var empId = fname.charAt(0) + mname.charAt(0) + lname.charAt(0) + '-' + birthdate.join('');
$("#empId").val(empId);
});
});
It's a straightforward translation of your Java code, wrapped in a jQuery event handler, and using .val() to get the values from the input fields.
DEMO
Beaten to it but still posting. This is same solution using jQuery
$(function(){
$( "#fname,#mname,#lname,#dob").keyup(function( event ) {
if ( event.which == 13 ) {
event.preventDefault();
}
//you probably want to do a bit more checking of the DOB value - such as length etc., I am merely stripping all non numerics from it
id = $("#fname").val().charAt(0) + $("#mname").val().charAt(0) + $("#lname").val().charAt(0) + "-" + $("#dob").val().replace(/\D/g,'');
$("#empId").val(id);
});
})
Demo

Categories

Resources