Javascript - get a date from an HTML input - javascript

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>.

Related

Selecting same element using class in JQuery [duplicate]

This question already has answers here:
Modify the value of each textfield based on original value using jQuery
(3 answers)
Closed last year.
I have lot of date fields in my application. IDs can't help, I want to format date fields using class. While trying to format the date, Holder2 date is also changed to Holder1's date, PFB
$(document).ready(function(){
$('.date').val($.format.date($('.date').val(), "MM/dd/yyyy hh:mm a"));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-dateFormat/1.0/jquery.dateFormat.min.js"></script>
<html>
<head>
<title>Test</title>
</head>
<body>
<div>
Holder 1:<input class="date" type="text" value="Mon Feb 06 00:30:00 IST 2017"><br>
Holder 2:<input class="date" type="text" value="Sun Mar 12 11:06:00 IST 2017">
</div>
</body>
</html>
Current Output:
Holder 1: 02/06/2017 12:30 AM
Holder 2: 02/06/2017 12:30 AM
Expected Output:
Holder 1: 02/06/2017 12:30 AM
Holder 2: 03/12/2017 11:06 AM
PS: type is mentioned as text because if mentioned as date, chrome shows its own datepicker. Both my custom datepicker and chrome's are loaded at the same time. Help me out please. Thanks.
You need to do the elements one at a time, which you can do with an .each() loop, or, more conveniently, by providing a callback function to the .val() method. The function you provide will be called once for each element, and will receive the current value of the field as an argument; whatever value you return will be set as the value.
$(document).ready(function(){
$('.date').val(function(i, oldVal) {
return $.format.date(oldVal, "MM/dd/yyyy hh:mm a");
});
});
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-dateFormat/1.0/jquery.dateFormat.min.js"></script>
<html>
<head>
<title>Test</title>
</head>
<body>
<div>
Holder 1:<input class="date" type="text" value="Mon Feb 06 00:30:00 IST 2017"><br>
Holder 2:<input class="date" type="text" value="Sun Mar 12 11:06:00 IST 2017">
</div>
</body>
</html>
there is a formatting using css classes right in the documentation.
https://github.com/phstc/jquery-dateFormat
$(document).ready(function() {
var longDateFormat = "MM/dd/yyyy hh:mm a";
jQuery(".date").each(function(idx, elem) {
jQuery(elem).val(jQuery.format.date(jQuery(elem).val(), longDateFormat));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-dateFormat/1.0/jquery.dateFormat.min.js"></script>
<div>
Holder 1:
<input class="date" type="text" value="Mon Feb 06 00:30:00 IST 2017">
<br> Holder 2:
<input class="date" type="text" value="Sun Mar 12 11:06:00 IST 2017">
</div>
The $('.date') selector will apply the change to all jQuery elements matching that selector, but will get the val from the first element matching the query. To get the val from the element you'll be formatting, you can use jQuery's .each(), along with $(this), to make sure you're targeting the current matched element.
$(document).ready(function(){
$('.date').each(function() {
$(this).val($.format.date($(this).val(), "MM/dd/yyyy hh:mm a"));
});
});
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-dateFormat/1.0/jquery.dateFormat.min.js"></script>
<html>
<head>
<title>Test</title>
</head>
<body>
<div>
Holder 1:<input class="date" type="text" value="Mon Feb 06 00:30:00 IST 2017"><br>
Holder 2:<input class="date" type="text" value="Sun Mar 12 11:06:00 IST 2017">
</div>
</body>
</html>
you can not do like this, because at end you see the all inputs have same result, in fact the first result added to all inputs.
you should use each()
$('.date').each(function(index){
$(this).someMethod()
});

How to use html form time input in Javascript local storage?

I'm trying to get time input in local storage but couldn't succeed it so far.
html part of the time input field of the form:
<label for="time"><p>Start</p></label>
<input type="time" id="time" name="time" min="09:00" max="17:00"/>
javascript:
function getTime(){
globalTime = document.getElementById("time").value;
localStorage.setItem("timeData", globalTime);
}
function inputTime(){
var newTime = localStorage.getItem("timeData");
alert(newTime);
}
When I call the inputTime function, I get empty alert box, which means I can't get the time input.
I'd be grateful if you could tell me what is the reason and how can I fix it.
Use .addEventListener() to attach input event to #time element. Attach click event to <button> elements to set and get value of localStorage
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<label for="time">
<p>Start</p>
</label>
<input type="time" id="time" name="time" min="09:00" max="17:00" value=""/>
<br />
<br />
<button id="setTime">
Set time
</button>
<button id="test">
Get time
</button>
<script>
document.getElementById('time').addEventListener('input', getTime);
document.getElementById('test').addEventListener('click', inputTime);
document.getElementById('setTime').addEventListener('click', setTime)
var globalTime;
function getTime() {
globalTime = document.getElementById("time").value;
console.log(globalTime)
}
function setTime() {
localStorage.setItem("timeData", globalTime);
}
function inputTime() {
var newTime = localStorage.getItem("timeData");
alert(newTime);
}
</script>
</body>
</html>
plnkr http://plnkr.co/edit/AzbVoqkGQwLXGlRV9CQd?p=preview

JS alert if inputted date 2 <= date 1

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!

JavaScript time in text field and not updating

Not sure why this JavaScript inst placing the time within the blank text field and updating the time every second. I am trying to get the JavaScript to have a label at the top that says Current Time then a text field that has the current time that is updated every second.
<html>
<head>
<title>Timer</title>
<script language="javascript" type="text/javascript">
var dateform
speed=2000
tid=0;
function dodate()
{
f.date.value=new Date();
tid=window.setTimeout("dodate()",speed);
}
function start(x)
{
f=x
tid=window.setTimeout("dodate()",speed);
}
function cleartid()
{
window.clearTimeout(tid);
}
</script>
</head>
<body onload="start(document.dateform) ;">
<center>
The Digital Clock
<FORM name="dateform" action="post">
<input type="text" name="date" size=30>
</FORM>
</center>
</body>
</html>
The method you need to use is setInterval and make little changes:
var dateform
speed=1000
tid=0;
function dodate()
{
f.date.value=new Date();
}
function start(x)
{
f=x
tid=window.setInterval("dodate()",speed);
}
function cleartid()
{
window.clearTimeout(tid);
}

jquery datepicker code not working (set specific date as default)

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");

Categories

Resources