set a value of select option field from the datepicker field - javascript

i have a booking form with checkin, nights, and chckout
the user select chckin date, and after that he choose number of nights, its reflect on the checkout field date
(if the checkin is to 08/08/19 and the user select 4 nights the checkout will be 12/08/19)
now.. what i want is if the user change the checkout date its reflect on the nights value
i already did the change from the nights select to checkout filed
$( ".nights" )
.change(function () {
$( this ).each(function() {
var nights = $('.nights-field').val();
var nightsVAr = "+" + nights + "d";
$( ".checkout-field" ).datepicker().datepicker("setDate", nightsVAr);
});
})
.change();
what i have truble with is the checkout field to nights
i need to calculate somehow the date of checkout minus the checkin and set the number of nights in the select field

try to use momentjs lib,
it will be something like this
var from = moment(fromDate);
var to = moment(toDate);
var nights =from.diff(to, 'days')

If you manipulate a lot of date I recommend using moment. Some other libraries as FullCalendar already use it.
Jquery solution :
Idea : getting the date in your form, gettings it timestamps, do the diff and convert the ms in day unit.
Using Math.round to get a int & Math.abs() for getting always a positive number.
$(document).ready(() => {
var arrival = $("input#arrival");
var departure = $("input#departure");
var msInDay = 1000 * 60 * 60 *24; // number of ms in a day;
$("input[type='date']").change(() => {
if (arrival.val() && departure.val()) {
dateArrival = new Date(arrival.val());
dateDeparture = new Date(departure.val());
var days = Math.round(Math.abs((dateArrival.getTime() - dateDeparture.getTime())) / (msInDay)); // getting time stamps of each date.
console.log("nights :" +days);
}
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="date" id="arrival">
<input type="date" id="departure">

Here I provide code which set nights field when we change checkout date field with simple jquery code with date and math function.
If your checkout date field is less than your checkin date field, then it will set nights field as 0 and show console log with error message.
$(".checkout-field")
.change(function () {
var nights = $('.nights-field').val();
var checkInDate = new Date($(".checkin-field").val());
var checkOutDate = new Date($(".checkout-field").val());
if(checkOutDate <= checkInDate) {
console.log("error dates are not valid");
$(".nights-field").val(0);
}
else {
var diffDate = checkOutDate - checkInDate;
var days = Math.floor(((diffDate % 31536000000) % 2628000000)/86400000);
$(".nights-field").val(days);
}
})

Related

How to do date validation with moment library in JavaScript?

I have a textbox: txtDepartureDate where a user can select the departure date. If the selected date is before today, then I was to show an error message. I have tried using the moment library in Javascript to achieve this and also used the oninput() event handler. I am trying to subtract today's date with the departure date to get the total number of days and if this is less than or equal to zero, then lblError should display the error message. The validation part is not working for me.
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>
This is how it is done:
var inputDate = moment([1990, 0, 01]);
var todayDate = moment().toDate();
inputDate.diff(todayDate, 'days')
You have to get entered input date in the above format.

Age validation using dd/mm/yyyy

I am trying to validate a form I have for age validating using javascript but it doesn't seem to be working.. not sure why.
Basically the date of birth is entered : dd/mm/yyyy and I need to make sure that in order to submit the form the age of the person is between 15 - 80.. I have tried validating this way but doesn't seem to work.
Html
<label>
Date of birth:
<input type="text" name="birth date" id="DOB"
placeholder="dd/mm/yyyy" maxlength="10" pattern="\d{1,2}\/\d{1,2}\/\d{4}"
required="required"/>
</label>
Javascript
var birthDate = document.getElementById("DOB").value;
if (2019 - birthDate < 15 || 2019 - birthDate > 80) {
errMsg =errMsg + "your age must be between 15 and 80\n";
result = false;
}
if (errMsg !== "") {
alert(errMsg);
}
return result;
So, based on your comment, you have a text box as such:
<form>
<input type="text" name="birth date" id="DOB" placeholder="dd/mm/yyyy" maxlength="10" pattern="\d{1,2}\/\d{1,2}\/\d{4}" required="required"/></label>
</form>
Therefore, document.getElementById("DOB").value; will be of the format dd/mm/yyyy.
So, if you are just checking the year, this should do the trick:
onload = function() {
var form = document.getElementById("form"); //assuming this is your form's ID
form.onsubmit = validate;
}
function checkAge() {
var currentYear = new Date().getFullYear();
var birthDate = document.getElementById("DOB").value;
var errMsg = ""; //this line was missing from my code, and preventing it from working.
//turning "dd/mm/yyyy" into an array of the form { "dd", "mm", "yyyy" }, and taking the "yyyy" part
var birthYear = birthDate.split("/")[2];
var age = currentYear - birthYear;
if (age < 15 || age > 80) {
errMsg =errMsg + "your age must be between 15 and 80\n";
result = false;
}
if (errMsg !== "") {
alert(errMsg);
return false; //form won't submit
}
return true; //form will submit
}
As you can see, I also used getFullYear() so that we don't hard code a fixed current year.
But it would probably be cleaner if you use an <input type="date"> element rather than a text box.
document.getElementById("DOB").value is a string, not a date, so you need to convert it. For that there are different methods; one is to convert the string to YYYY-MM-DD format and pass that to the Date constructor.
Moreover, someone's age changes on their birthday, not at the change of a calendar year, so you need a different logic to get their age. One way is to precalculate the date of 15 years ago and of 81 years ago, and test that the entered birthdate lies between these two extremes.
var DOB = document.getElementById("DOB");
var output = document.getElementById("output");
var go = document.getElementById("go");
var fifteenYearsAgo = new Date();
fifteenYearsAgo.setFullYear(fifteenYearsAgo.getFullYear() - 15);
var eightyOneYearsAgo = new Date();
eightyOneYearsAgo.setFullYear(eightyOneYearsAgo.getFullYear() - 81);
// Function returns true when age is OK, false otherwise
function check() {
var birthDate = new Date(DOB.value.replace(/(..)\/(..)\/(....)/, "$3-$2-$1"));
return birthDate <= fifteenYearsAgo && birthDate > eightyOneYearsAgo;
}
go.addEventListener("click", function() {
if (check()) {
output.textContent = "Your age is OK";
} else {
output.textContent = "Your age must be between 15 and 80";
}
});
Birthdate: <input id="DOB"><button id="go">Go</button>
<div id="output"></div>
HTML5
If you are certain about your clients having HTML5 support, then use type="date" for your input element, and dynamically set the min and max attributes of a date typed input element and rely on form validation. If the form gets into the submit handler, you can be sure the validations passed:
var DOB = document.getElementById("DOB");
var form = document.querySelector("form");
var fifteenYearsAgo = new Date();
fifteenYearsAgo.setHours(0, 0, 0, 0);
fifteenYearsAgo.setFullYear(fifteenYearsAgo.getFullYear() - 15);
var eightyOneYearsAgo = new Date();
eightyOneYearsAgo.setHours(0, 0, 0, 0);
eightyOneYearsAgo.setFullYear(eightyOneYearsAgo.getFullYear() - 81);
// Border case: in leap years next condition could be false
if ((new Date()).getDate() === eightyOneYearsAgo.getDate()) {
eightyOneYearsAgo.setDate(eightyOneYearsAgo.getDate()+1);
}
DOB.setAttribute("min", eightyOneYearsAgo.toLocaleString("se").slice(0,10));
DOB.setAttribute("max", fifteenYearsAgo.toLocaleString("se").slice(0,10));
form.addEventListener("submit", function(e) {
alert("Your age is OK");
e.preventDefault();
return false;
});
function validationMessage() {
DOB.setCustomValidity("");
const msg = DOB.checkValidity() ? ""
: DOB.validity.valueMissing ? "This field is required"
: DOB.validity.rangeOverflow ? "You must be at least 15"
: DOB.validity.rangeUnderflow ? "You must be at most 80"
: "Enter a valid date"
DOB.setCustomValidity(msg);
}
DOB.addEventListener("input", validationMessage);
validationMessage();
<form>
<label>
Date of birth:
<input type="date" name="birth date" id="DOB" required="required"/>
</label>
<button id="go">Go</button>
</form>
document.getElementById("DOB").value; will give you something like 10/10/2000 and performing arithmetic operations on this string will result in NaN. That must be causing an issue.
Validating date is a more complex than you imagine. There are a lot of things that you need to consider. Use libraries like moment to help you in validating dates.
Edit: Use moment's Difference method to calculate the age.
You can use built in min and max props for input. Try something like this.
<p>Enter a number and click OK:</p>
<input id="id1" type="number" min="15" max="80" required>
<button onclick="myFunction()">OK</button>
<p>If the age is less than 15 or greater than 80, an error message will be
displayed.</p>
<p id="demo"></p>
<script>
function myFunction() {
var inpObj = document.getElementById("id1");
if (!inpObj.checkValidity()) {
document.getElementById("demo").innerHTML = inpObj.validationMessage;
} else {
document.getElementById("demo").innerHTML = "Input OK";
}
}
</script>
Theoretically this should work.
Since you are using pattern and required I assume that you want the error message (if the age is out of range) to be shown to the user in the same way as if the entered date is in the wrong format or is missing. That can be achieved with setCustomValidity.
If you add an event listener of the input event on the DOB-element, you can run a function that checks if the entered age is in rage. It will set the custom error message if the age is out of range, or if the entered date is invalid. Otherwise it let the browser handle the error (if it is missing or of wrong pattern).
function validateDOB(event) {
const minAge = 15, maxAge = 80;
// No custom error message. The broswer will complain if the input isn't in the
// correct form, or if the value is missing since the element has "pattern" and
// and "required".
this.setCustomValidity('');
// Check if there are any other errors
if ( !this.validity.valid ) return;
// Check format of input, and split it into parts
const dobArrayText = this.value.trim().match(/^(\d{1,2})\/(\d{1,2})\/(\d{4})$/);
// dobArrayText is null if not in correct format. Let the broswer handle the error.
if (!dobArrayText) return;
// Decode dobArrayText to numeric values that can be used by the Date constructor.
const dob = {
year : +dobArrayText[3],
month : (+dobArrayText[2]) - 1, // month is zero based in date object.
day : +dobArrayText[1]
}
const dobDate = new Date( dob.year, dob.month, dob.day );
// Check validity of date. The date object will accept 2000-99-99 as input and
// adjust the date to 2008-07-08. To prevent that, and make sure the entered
// dobDate is a valid date, I check if the entered date is the same as the parsed date.
if (
!dobDate
|| dob.year !== dobDate.getFullYear()
|| dob.month !== dobDate.getMonth()
|| dob.day != dobDate.getDate()
) {
this.setCustomValidity('Invalid date');
return;
}
// Calc minAgeDate and maxAgeDate
const minAgeDate = new Date(dob.year + minAge, dob.month, dob.day);
const maxAgeDate = new Date(dob.year + maxAge, dob.month, dob.day);
// Get todays date and set Hours, Minutes, Seconds and Milliseconds to 0.
const todayTimestamp = new Date().setHours(0,0,0,0);
// Check validity and set a custom error message if needed.
if ( todayTimestamp < minAgeDate ) {
this.setCustomValidity(`Sorry, you must be older than ${minAge} years old`);
}
else if ( todayTimestamp >= maxAgeDate ) {
this.setCustomValidity(`Sorry, you must be younger than ${maxAge} years old`);
}
}
function formInit() {
document.getElementById('DOB').addEventListener("input", validateDOB);
}
window.addEventListener('DOMContentLoaded', formInit);
<form id="myForm">
<label>
Date of birth:
<input type="text" name="birth_date" id="DOB"
placeholder="dd/mm/yyyy" maxlength="10" pattern="\d{1,2}\/\d{1,2}\/\d{4}"
required="required"/>
</label>
<button type="submit">Submit</button>
</form>

How to pass date id from one jsp to another jsp page

I am calculating the price of a ticket with discount on weekdays and weekends based on the time duration.So, i gave inputs of duration and date using datepicker plugin which is in Above Page. For this i am getting proper result.But i have to create two different jsp pages(date.jsp and cal.jsp).
In 1st jsp page(date.jsp) i am selecting date using datepicker. And in 2nd jsp page(cal.jsp)
I have written a method ->[caluculate(#dateid,#duratiionid)] to calulate the price by taking inputs as time duration.
Here My Question is how shall i pass [#dateid] from 1st jsp page(date.jsp) to 2nd jsp page(cal.jsp)
so that i can pass both the id's in this method->[caluculate(#dateid,#duratiionid)].
<div id="container">
<div id="form">
<form id="book_court">
<div class="fieldset">
<fieldset>
<legend class="visuallyhidden">Booking Details</legend>
<h2>Booking Details</h2>
<p>
<label for="date">Date<br/><span id="dateNote">Firefox does not have a HTML5 datepicker yet.</span></label>
<input type="date" name="date" id="date" min="today" required />
</p>
<p>
<label for="tickets_duration"> Hours</label>
<input type="number" min="1" name="tickets_duration" id="tickets_duration" required />
</p>
<p>
<label>Total Price</label>
<span id="total_price">(enter data first)</span>
</p>
<div id="submit_wrapper">
<input type="submit" id="submit" value="Book Court" />
</div>
</fieldset>
</div>
</form>
</div>
</div>
<script id="worker" type="javascript/worker">
self.onmessage = function msgWorkerHandler(event){
var jsonString = event.data;
var day = jsonString.day;
var tickets_duration = jsonString.tickets_duration;
// set price of each hours as Rs. 200 and 300
var totalPriceOnWeekday = tickets_duration * 200;
var totalPriceOnWeekends=tickets_duration * 300;
// 10% discount if on weekday and 15% on weekends
if(day > 0 && day < 6){
totalPriceOnWeekday = totalPriceOnWeekday - 0.10 * totalPriceOnWeekday;
postMessage("₹ " + totalPriceOnWeekday);
}else if(day == 0 || day == 7){
totalPriceOnWeekends = totalPriceOnWeekends - 0.15 * totalPriceOnWeekday;
postMessage("₹ " + totalPriceOnWeekends);
}
}
</script>
<script>
$(document).ready(function(){
// first check the movies already book
// apply jQuery UI Redmond theme to 'Book Tickets' button
$("#submit").button();
// calculateTotalPrice on keyup or on change of movie/date/tickets
$("#date, #tickets_duration").change(calculateTotalPrice);
// on form submit
$("#book_court").submit(function(event){
// prevent on submit page refresh
event.preventDefault();
// check locally stored data
// clear the form
$( '#book_court' ).each(function(){
this.reset();
});
// reset (enter data first) message
$("#total_price").html("(enter data first)");
// update movies booked list
});
// set minimum date in datepicker as today
var today = new Date().toISOString().split('T')[0];
document.getElementsByName("date")[0].setAttribute('min', today);
});
function calculateTotalPrice(){
if($("#tickets_duration").val() != "" && $("#date").val() != ""){
if(window.Worker){
// create web worker
var blob = new Blob(
[document.querySelector("#worker").textContent],
{type: 'text/javascript'});
var worker = new Worker(window.URL.createObjectURL(blob));
worker.onmessage = function(event){
$("#total_price").html(event.data);
}
worker.onerror = function(errorObject){
$("#total_price").html("Error: " + errorObject.message);
}
var date = new Date($('#date').val());
// get day
var day = date.getDay();
// get number of booked shows
// send JSON data to worker
var jsonData = {'day': day, 'tickets_duration': Number($("#tickets_duration").val())};
worker.postMessage(jsonData);
}
}
}
</script>
If you want to share a value cross-pages, you can use cookie to store the value. Another option is localStorage/sessionStorage if you are using HTML5.
So, in the first page (date.jsp), when user select a date, you can store that selection to cookie, in the second page (cal.jsp) you can read that value from cookie and then do your calculation.
I suppose that you are able to post the date string back to servlet. In the servlet, you are using that date string to check for ticket validity. You just don't know how to check if the date is weekday or weekends. If so you can you the java.util.Calendar for that purpose.
EDITED
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
Date yourDate = formatter.parse(dateInString);
Calendar c = Calendar.getInstance();
c.setTime(yourDate);
int dayOfWeek = c.get(Calendar.DAY_OF_WEEK);

how to add days / weeks from separate field in start date to get end date in datepicker?

In my form , I have 3 fields.
<input name="course_duration" id="course_duration" type="text"> (A numeric value which denotes 'Weeks'
<input name="course_start" id="course_start" type="text">
<input name="course_end" id="course_end" type="text">
I am using datepicker jquery and I want to fillup course_end date automatically by adding number of weeks from value inserted in course_duration field + course_start date
currently I am using following javascript code to popup calendar and selecting dates for course_start and course_end manually.
<script type="text/javascript">
$(document).ready(function() {
$('#course_start').datepicker({dateFormat: 'yy-mm-dd'});
$('#course_end').datepicker({dateFormat: 'yy-mm-dd'});
});
</script>
JSFIDDLE
// Get the week from course_duration
var weeks = $('#course_duration').val();
// Get the selected date from startDate
var startDate = $('#course_start').datepicker('getDate');
var d = new Date(startDate);
// Add weeks to the selected date, multiply with 7 to get days
var newDate = new Date(d.getFullYear(), d.getMonth(), d.getDate() + weeks * 7);
// Set the new date to the course endDate
$('#course_end').datepicker('setDate', newDate);
Demo

PHP: Date range selection automatically

I have 3 input fields all together.
Contract period: 1 years(for example)
start date : 30 - 1- 2012 (for example)
end date : ????
(Can we get the end date automatically according to the contract period mentioned, which mean if the date after 1 year is 30-1-2013 can we get it automatically in the third field after mentioning the first and second field).
Possible, using onSelect option of jQuery datepicker.
1) get the value of contract year and parse it as integer.
var addYears = parseInt($('#contract').val(), 10);
2) Split the selected date in startDate, as below
var t = date.split('/');
3) Now add the years and parse it as Date object.
var fin = new Date(parseInt(t[2], 10) + addYears, --t[0], t[1]);
Finally,
HTML:
In years only:
<input id="contract" type="text" />
<input id="start" type="text" />
<input id="end" type="text" />
JS:
$('#end').datepicker();
$('#start').datepicker({
onSelect: function (date, args) {
var addYears = parseInt($('#contract').val());
var t = date.split('/');
var fin = new Date(parseInt(t[2], 10) + addYears, --t[0], t[1]);
$('#end').datepicker("setDate", fin);
}
});
JSFiddle

Categories

Resources