I want to get inputs from my HTML process the info in my JS and send a result back to the HTML. In the example the JS calculates the stay of a person in an accommodation. I just need to get their check-in and check-out dates.
var date1 = new Date("7/13/2010");
var date2 = new Date("12/15/2010");
var timeDiff = Math.abs(date2.getTime() - date1.getTime());
var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));
<form>
<p>Select your Check-in date please</p>
<input id="inDate" type="date">
</br>
<p>Select your Check-out date please</p>
<input id="outDate" type="date">
</br>
<span>You are staying</span><span id="stay"></span> <span> days with us.</span>
</br>
</form>
To get "Check-in date":
var inDate=document.getElementById("inDate").value;
To get "Check-out date"
var outDate=document.getElementById("outDate").value;
If you want the date picker just import jquery UI library it will allow you insert the date calendar directly
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<form>
<p>Select your Check-in date please</p>
<input id="inDate" type="date">
</br>
<p>Select your Check-out date please</p>
<input id="outDate" type="date">
</br>
<span>You are staying</span><span id="stay"></span> <span> days with us.</span>
</br>
<link href="https://code.jquery.com/ui/jquery-ui-git.css" rel="stylesheet" type="text/css" />
<script src="https://code.jquery.com/jquery-git.js"></script>
<script src="https://code.jquery.com/ui/jquery-ui-git.js"></script>
</form>
</body>
</html>
Add add this follow javascript code:
$(function() {
$( "#inDate, #outDate" ).datepicker();
});
Here is the link to jsbin: https://jsbin.com/kunugi/edit?html,js,output
Read the code comments ,hope this will help
function calc() {
// get corresponding value from input
var inDate = document.getElementById('inDate').value;
var outDate = document.getElementById('outDate').value;
// allow calculations if both input fields have values, otherwise error can occur while calculating date
if (inDate && outDate) {
// convert to date format
var date1 = new Date(inDate);
var date2 = new Date(outDate);
// code for checking date1 > date 2 if you want
//calculations
var timeDiff = Math.abs(date2.getTime() - date1.getTime());
var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));
//for Displaying in html
document.getElementById('stay').innerHTML = diffDays;
}
}
// adding event so that when we change any one of the field, the functuion will calculate the daydiff and display in the html page
document.getElementById('outDate').addEventListener("change", calc);
document.getElementById('inDate').addEventListener("change", calc);
<form>
<p>Select your Check-in date please</p>
<input id="inDate" type="date">
<p>Select your Check-out date please</p>
<input id="outDate" type="date">
<span>You are staying </span><span id="stay"></span> <span> days with us.</span>
</form>
Related
I have 2 input date fields
1.1. One is for the start date and this should like:= 01/01/current-year(01/01/2022, the current year is 2022 so it should take this year and if the current year is 2023 then this should be like:= 01/01/2023).
1.2. the Second field should have the current date like:= 20/12/2022
I have attached the screenshot for your reference
enter code here
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Date Picker</title>
</head>
<body>
<label for="start-date">Start Date</label>
<input class="date-picker">
<label for="end-date">End Date</label>
<input class="date-picker">
</body>
</html>
<!-- begin snippet: js hide: false console: true babel: false -->
Any help with this requirement would be very grateful Thanks in Advance
Hi Karthik first i notice you should give an ID to the date picker elements in order to target them individiually.
Here's how html will be:
<label for="date-start">Start Date</label>
<input class="date-picker" id="date-start">
<label for="end-date">End Date</label>
<input class="date-picker" id="date-end">
And then javascript will be:
//current month and year
var yearNow = new Date().getFullYear();
var monthNow = new Date().getMonth() + 1;
//set the start date's field value to current year
document.getElementById('date-start').value = "01/01/" + yearNow;
//set the value of the end date field to current date
document.getElementById('date-end').value = monthNow + "/" + new Date().getDate() + "/" + yearNow;
I did .getMonth() + 1 because getMonth() begins with 0.
Update on the light of your comment on my answer:
If I understand correctly, you need to add a checkbox which toggles the delete button viewability + you will need another button when clicked to show the Delete button:
Additional HTML:
<input type="checkbox" id="checkbox">
<label for="checkbox">Show delete button</label>
<button id="delete-button" style="display:none">Delete</button>
<button id="select-all">Select All</button>
Additional Javascript:
var checkbox = document.getElementById('checkbox');
var deleteButton = document.getElementById('delete-button');
//event listener to toggle the delete button viewability
checkbox.addEventListener('change', function() {
if (checkbox.checked) {
deleteButton.style.display = 'block';
} else {
deleteButton.style.display = 'none';
}
});
//event listener for the "Select All" button which shows the delete button:
document.getElementById('select-all').addEventListener('click', function() {
deleteButton.style.display = 'block';
});
I have two date inputs. When I choose start date, I want jquery to automatically generate an end date that's 3 months later.
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
<script src="https://kit.fontawesome.com/04b00d367c.js"></script>
<script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
<div class="container">
<div class="col-md-6">
<label class="text-black" for="dpradzia">Start Date</label>
<input type="date" id="darbo_pradzia" name="darbo_pradzia" class="form-control">
</div>
<div class="col-md-6">
<label class="text-black" for="bandomasis_laikotarpis">End date </label>
<input type="date" id="bandomasis_laikotarpis" name="bandomasis_laikotarpis" class="form-control">
</div>
</div>
You should listen to change events of the first input and create a new Date with its value. After that, you can add 3 months to this object using new Date(date.setMonth(date.getMonth()+3)). The new date with the extra 3 months should be formatted into yyyy-mm-dd and set to the value of the second input. The complete program is:
$(document).ready(function() {
$('#darbo_pradzia').change(function(){
let date = new Date($(this).val());
let newDate = addMonths(date, 3);
var formatted = newDate.toISOString().split('T')[0]; //yyyy-mm-dd
console.log(formatted);
$('#bandomasis_laikotarpis').val(formatted);
});
//add months to date function
function addMonths(date, months) {
var d = date.getDate();
date.setMonth(date.getMonth() + +months);
if (date.getDate() != d) {
date.setDate(0);
}
return date;
}
});
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
<script src="https://kit.fontawesome.com/04b00d367c.js"></script>
<script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
<div class="container">
<div class="col-md-6">
<label class="text-black" for="dpradzia">Start Date</label>
<input type="date" id="darbo_pradzia" name="darbo_pradzia" class="form-control">
</div>
<div class="col-md-6">
<label class="text-black" for="bandomasis_laikotarpis">End date </label>
<input type="date" id="bandomasis_laikotarpis" name="bandomasis_laikotarpis" class="form-control">
</div>
</div>
EDIT :
According to #RobG's comment, adding a number of months to a date object has several unique test cases that need to be taken into consideration. Therefore, I used his answer in this post to achieve this operation.
<script>
$('#darbo_pradzia').on('focusout', function(){
let startDate = new Date($('#darbo_pradzia').val());
let endDate = new Date(startDate);
endDate.setMonth(endDate.getMonth()+3);
let day = ("0" + endDate.getDate()).slice(-2);
let month = ("0" + (endDate.getMonth() + 1)).slice(-2);
let date = endDate.getFullYear()+"-"+(month)+"-"+(day) ;
$('#bandomasis_laikotarpis').val(date);
})
</script>
You can read the value on the onchange event or focusout event. Read the date and you can copy the inserted date from the Date constructor. Increase the month, no problem if you overflow the 12 months because automatically the year is increased and the month value scaled between [0-11]. Now to write the date in the input date field there are two problem:
Date control in HTML 5 accepts in the format of Year - month - day
If the month is 5, it needs to be set as 05 not 5 simply. The same thing for day field also.
Add the script downwards in the page, or add a ready/onload event
I have a form where a visitor can make a lodging reservation with an arrival date and departure date. If they click on an input field a calendar pops up for them to select a date. How can I add a popup JS alert if the departure date is <= the arrival date? My code is as follows:
<head>
...
<script type="text/javascript" src="js/CalendarPopup.js"></script>
<script type="text/javascript">document.write(getCalendarStyles());</script>
...
</head
<script type="text/javascript" id="jsArrive">
var now = new Date();
var yesterday = new Date(now);
yesterday.setDate(now.getDate() - 1);
var calArrive = new CalendarPopup("divArrive");
</script>
<b>Arrive:</b>
<input type="text" name="dateArrive" value="" size="15" onClick="calArrive.select(document.forms[0].dateArrive,'dateArrive','d/M/yyyy'); return false;" title="calArrive.select(document.forms[0].dateArrive,'dateArrive','d/M/yyyy'); return false;" id="dateArrive" />
</p>
<div id="divArrive" style="position:absolute;visibility:hidden;background-color:white;layer-background-color:white;"></div>
<script type="text/javascript" id="jsDepart">
var now = new Date();
var yesterday = new Date(now);
yesterday.setDate(now.getDate() - 1);
var calDepart = new CalendarPopup("divDepart");
</script>
<b>Depart:</b>
<input type="text" name="dateDepart" value="" size="15" onClick="calDepart.select(document.forms[0].dateDepart,'dateDepart','d/M/yyyy'); return false;" title="calDepart.select(document.forms[0].dateDepart,'dateDepart','d/M/yyyy'); return false;" id="dateDepart" />
<input type="submit" value="Go" name="submit" />
</p>
<div id="divDepart" style="position:absolute;visibility:hidden;background-color:white;layer-background-color:white;"></div>
It's as simple as comparing the two dates, like so:
if (departureDate <= arrivalDate) {
alert ("You must make sure your departure is before your arrival!);
}
I suggest you run the above if statement when the user has entered there arrival date. So you'd use an onChange event on each of the inputs incase they go back and change there departure date!
I am currently trying to take the value from an HTML input (below)
<input type="date" id="dateInput" />
and put it into a javascript variable so I can use it for other things. I currently am using the code below.
var input = document.getElementById("dateInput").value;
var dateEntered = new Date(input);
But when I test those variables, it tells me that Input is "" and dateEntered is "Invalid Date".
I've tried the .valueAsDate instead of just .value as well. When I test those out, it tells me that Input is null and dateEntered is "Wed Dec 31 1969 19:00:00 GMT-0500 (Eastern Standard Time)" even though I entered today's date.
How would I fix this so that the javascript variables actually reflect the date I enter? I am using Google Chrome as my browser.
EDIT and UPDATE
For those who wanted my whole code, indentation is a little off sorry:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<title>Calculate Time</title>
<link rel="stylesheet" href="styles.css" />
<script src="modernizr.custom.05819.js"></script>
</head>
<body>
<header>
<h1> Calculate Time </h1>
</header>
<article align="center">
<div id="cities">
// My navigation links here (REMOVED)
</div>
<div id="caption">
Calculate the time elapsed since a date entered.
</div>
<div class="box">
<article>
<form>
<fieldset>
<label for="dateEntered">
Enter a Date
</label>
<input type="date" id="dateInput" />
</fieldset>
<fieldset class="button">
<button type="button" id="determineTime">Find Time</button>
</fieldset>
<fieldset>
<p>Time Elapsed is:</p>
<p id="time"></p>
</fieldset>
</form>
</article>
</div>
<div id="map"></div>
</article>
<script>
var input;
var dateEntered;
document.getElementById("dateInput").addEventListener("change", function () {
input = this.value;
dateEntered = new Date(input);
});
/* find and display time elapse */
function lookUpTime() {
// More code will go here later.
}
// add event listener to Find time button and clear form
function createEventListener() {
var submitButton = document.getElementById("determineTime");
if (submitButton.addEventListener) {
submitButton.addEventListener("click", lookUpTime, false);
} else if (submitButton.attachEvent) {
submitButton.attachEvent("onclick", lookUpTime);
}
document.getElementById("dateInput").value = "";
// clear last starting value on reload
document.getElementById("time").innerHTML = "";
// clear previous results on reload
}
if (window.addEventListener) {
window.addEventListener("load", createEventListener, false);
} else if (window.attachEvent) {
window.attachEvent("onload", createEventListener);
}
</script>
<script src="script.js"></script>
</body>
</html>
document.getElementById("dateInput").addEventListener("change", function() {
var input = this.value;
var dateEntered = new Date(input);
console.log(input); //e.g. 2015-11-13
console.log(dateEntered); //e.g. Fri Nov 13 2015 00:00:00 GMT+0000 (GMT Standard Time)
});
Basically you need to listen for the change of your date input, currently you were trying to get the value on load, when the picker has no date in it hence you get 'Invalid Date'
Make sure your script is executing after the DOM has fully loaded. To do this you can put your JS code in a function and call the function once the DOM has loaded, or just put your JS code at the end of your page, right before </body>.
I am trying to set the date to a specific one on page load so I'm trying this code:
<script type="text/javascript">
$(document).ready(function() {
var queryDate = new Date();
queryDate.setFullYear(2009,11,01);
$('#date').datepicker({defaultDate: queryDate});
$("input[type='submit']").click(function(e) {
e.preventDefault();
$.post("s.php", $("form").serializeArray(), function(message) {
window.location="v.php"
});
});
});
</script>
//The form part where is displays the datepicker:
<form action="#" method="POST">
<div data-role="fieldcontain">
<label for="date">Date:</label>
<input type="date" name="date" id="date" value="" />
<input type="submit" value="submit" />
</div>
</form>
The problem is that nothing's changing ... the default is still the current date :o/
Any ideas anyone please?
UPDATE: Tried this code:
var queryDate = new Date(2009,11,01);
$('#date').datepicker({defaultDate: queryDate});
$('#date').val(queryDate);
And the date is appearing in the input box but the calendar is not in the right month nor date ... Moving foward but still not working.
I'm not sure sure the suggested answer here is not working. As I have tested it display on the right month and year, but only not highlighted the date. This could be because the date format.
Try adding this code to have a default value on your date.
$('#date').val(queryDate);
Then you may see that the format is different with the date in date-picker. If you manage to set the right format with date-picker, you get the things you wanted.
Umm what if you tried this
new Date(year, month, day, hours, minutes, seconds, milliseconds)
var queryDate = new Date();
queryDate.setFullYear(2009,11,01);
$('#date').datepicker({defaultDate: queryDate});
Then the datepicker knows its a date object and how to handle it.
EDIT
Ok - all i did was copy the code exactly as you got it here several posts the same suggestion- and the code you edited. Added tags- inlcuded jquery and jquery ui..
I see no problem- the defuatl date is 2009.
</head>
<script src="jquery.min.js" type="text/javascript"></script>
<script src="jquery-ui.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
var queryDate = new Date();
queryDate.setFullYear(2009,11,01);
$('#date').datepicker({defaultDate: queryDate});
$("input[type='submit']").click(function(e) {
e.preventDefault();
$.post("s.php", $("form").serializeArray(), function(message) {
window.location="v.php"
});
});
});
</script>
</head>
<body>
//The form part where is displays the datepicker:
<form action="#" method="POST">
<div data-role="fieldcontain">
<label for="date">Date:</label>
<input type="date" name="date" id="date" value="" />
<input type="submit" value="submit" />
</div>
</form>
</body>
Result (no styles sheet attached)
Working example- tell me what is wrong
http://jsfiddle.net/ppumkin/nptgn/
Try this
var queryDate = new Date(2009,11,01);<br/>
$('#date').datepicker({defaultDate: queryDate});
I was having a similar problem, I solved it like this
$('.datepicker').datepicker({dateFormat: "yy-mm-dd", defaultDate: "+3m"} );
Try this
$('#mydate').val("2009-11-01");