Unable to access input date values with javascript - javascript

I've been using forms which upon submit call a function which makes use of the inputted data. So far this has worked fine with text, but switching to date inputs is causing me trouble.
I'm using the following code, but the "startDate", "endDate" values are empty.
<form onsubmit="myFunction()">
Start Date:
<input type="date" name="startDate" id="startDate">
End Date:
<input type="date" name="endDate" id="endDate">
<input type="submit">
</form>
<!-- Form to process above date submit -->
<script>
function myFunction() {
var locationID = "1";
var startDate = document.getElementById("startDate").value;
var endDate = document.getElementById("endDate").value;
var apiURL = "APIUrl" + locationID + "_" + startDate + "_" + endDate;
alert("The form was submitted" + apiURL);
$.get(apiURL, function( data ) {
$( ".result" ).html( data );
});
}
</script>
The alert gives me back the APIUrl, plus the location ID, but blank values for the dates.
Any ideas?
Thanks for your help.

You didn't specify what browser you are using.
Since you're already using jQuery, I recommend using it to retrieve the field values, i.e.
var startDate = $("#startDate").val();
var endDate = $("#endDate").val();
That would resolve browser inconsistencies that could play a part in your issue.

Your code work as expected in Chrome because it supports input date but this is not the case for IE, Firefox and Safari as you can see here : http://caniuse.com/#search=input%20date
It would probably be better if you use a library like JQuery-UI for the datepicker so it can be supported by all browsers

Related

How to have javascript presets today's date in HTML form

I am developing a project with Django.
I have an html webpage containing a form which has a date field.
I want javascript compile it with today's date as soon as my user lands on that webpage, so that he/she gets a kind of "default date".
I have in my html page (templates/aggiungi_terminologia.html), the date field:
<div class="form-group">
<label for="glossary_entry_input_21">Data di inserimento della terminologia</label>
<small id="inputHelp" class="form-text text-muted">Compilare solo se รจ nota la data di pubblicazione del documento fonte, altrimenti inserire la data di oggi.</small>
<input name="Data_inserimento_entry" type="date" value="01/01/1900" class="form-control" id="date_to_turn_into_today" placeholder="">
</div>
and then the javascript call at the end of the form:
{% load static %}
<script> src="{% static 'get_today_date.js' %}"</script>
And then, inside my javascript function (static/js/get_today_date.js):
var today = moment().format('DD/MM/YYYY');
document.getElementById("date_to_turn_into_today").value = today;
and since I am using moment.js, I added 'moment' in settings.py> INSTALLED_APPS ,
and to install moment I run on my console:
pip install django-staticfiles-moment
But when I run the server, all I get on that field is this:
My console is returning:
WARNINGS: app_glossario.glossary_entry.Data_inserimento_entry:
(fields.W161) Fixed default value provided.
HINT: It seems you set a fixed date / time / datetime value as default for this field. This may not be what you want. If you want to
have the current date as default, use django.utils.timezone.now
Why javascript is not replacing the date?
How can I make it work?
NOTE: the problem lies in the connection between js, html and django
Continue from comment about duplicated or not, take a look:
var now = new Date();
var day = ("0" + now.getDate()).slice(-2);
var month = ("0" + (now.getMonth() + 1)).slice(-2);
var today = now.getFullYear()+"-"+(month)+"-"+(day);
document.getElementById('inputDate').value = today;
<input type="date" id="inputDate" />
Please check this also.
I've seen similar behavior (where the input field shows a date placeholder instead of my desired date) when I provided a date string that was incorrectly formatted. The input element seems to need a format like yyyy-mm-dd.
Here's a pretty intuitive solution using vanilla JS. The default value of the input element will be the (locale-specific) date.
(And most of the further info you might want about JS Dates can be found here on MDN.)
const
// Selects input element
dateInput = document.getElementById("date"),
// Defines Date object
date = new Date(),
// Extracts component parts of Date object
year = date.getFullYear(),
month = date.getMonth(),
day = date.getDate(),
// Defines a function to add a leading zero if needed
pad = part => part < 10 ? "0" + part : part,
// Formats date to meet the `input` element's expectations -- like: `yyyy-mm-dd`
// (Adds +1 to month b/c `getMonth()` uses a zero-based array)
dateString = year + "-" + pad(month + 1) + "-" + pad(day);
// Inserts date string into input element
dateInput.defaultValue = dateString;
// Repeats this process for the "time" parts
/*
const
timeInput = document.getElementById("time"),
hours = date.getHours(),
minutes = date.getMinutes(),
seconds = date.getSeconds(),
timeString = pad(hours) + ":" + pad(minutes) + ":" + pad(seconds);
timeInput.defaultValue = timeString;
*/
<input id="date" type="date" />
<!--
// Optional input for time
<input id="time" type="time" />
-->
SOLVED
Here is what I did.
In a javascript file called
get_today_date.js
stored at path
static/js/get_today_date.js
I inserted
function get_today_date() {
var now = new Date();
var day = ("0" + now.getDate()).slice(-2);
var month = ("0" + (now.getMonth() + 1)).slice(-2);
var today = now.getFullYear()+"-"+(month)+"-"+(day);
document.getElementById('date_to_turn_into_today').value = today;
}
as suggested here https://stackoverflow.com/a/57953522/7658051 .
Then in the HTML page, before the closing </body> tag, I inserted
{% load static %}
<script type="text/javascript" src={% static "js/get_today_date.js" %}></script>
<script> get_today_date() </script>
and it works perfectly.
There was no neet to install the module moment, and even if my console returns
WARNINGS: app_glossario.glossary_entry.Data_inserimento_entry: (fields.W161) Fixed default value provided. HINT: It seems you set a fixed date / time / datetime value as default for this field. This may not be what you want. If you want to have the current date as default, use django.utils.timezone.now
my app works fine.
The previous code did not work just because I forgot to call the function in HTML, so I just had to add
get_today_date()
But in the end I am not sure if I correctly installed the moment module required for the previuos javascript script.

I have JS form with dynamic link based on date input, I need to output in DD-MM-YYYY format

I have a booking form where a user selects two dates. The user is then sent to an URL based on the date inputs:
<form class="availability-form" id="booking">
<input type="text" name="arrival" id="arrival" class="awe-calendar from" placeholder="Arrival Date">
<input type="text" name="departure" id="departure" class="awe-calendar to" placeholder="Departure Date">
<div class="availability-submit">
<button type="submit" id="button" class="awe-btn awe-btn-13">Submit</button>
</div>
</form>
I am using the following to navigate to the custom URL:
<script>
$(document).ready(function () {
$("#booking").on('submit', function (e) {
e.preventDefault();
window.location.replace(
"http://www.example.com/page/" +
$("#arrival").val() + "/" +
$("#departure").val()
);
});
});
</script>
The code does a great job at sending visitors to the URL with date format MM/DD/YYYY.
However, the booking service I am using requires the date in DD-MM-YYYY. I would change the entire website to that format, but it is not universally recognized.
The easy solution would be to use three different inputs for the day, month, and year, but I was hoping I can keep my pretty looking calendar popup, and convert the format as the user submits the form. Any ideas on how to do this?
Thanks for the help.
Edit:
Here's where I'm at:
var arrive = document.getElementById("arrival").value.split('/');
var depart = document.getElementById("departure").value.split('/'); $(document).ready(function () {
$("#booking").on('submit', function (e) {
e.preventDefault();
window.location.replace("http://www.example.com/page/" + arrive[0] + "-" + arrive[1] + "-" + arrive[2] + "/" + depart[0] + "-" + depart[1] + "-" + depart[2]);
}); });
The URL I am sent to has only undefined values:
http://www.example.com/page/-undefined-undefined/-undefined-undefined
I'm not sure why it is not picking up the inputs. I also have no clue why the arrive[0] and depart[0] do not even show up.
Any additional help would be greatly appreciate.

How to calculate age from given data on input field?

I have searched but i didn't get perfect solution of my issue.I can calculate age in normal way.But i haven't any idea how can i calculate age from given data on input field.I have used jQuery DatePicker for input field.My code:
$birthday = new DateTime('1970-02-01');
$to = new DateTime('today');
echo $birthday ->diff($to)->y.' Years, '.$birthday ->diff($to)->m.' Months, '.$birthday ->diff($to)->d.' Days ';
This is my field:
Now i want $birthday will be dynamic and it will insert and want to show immediately age calculation without page load. Have any clue? Thanks in advance.
The jQuery datepicker displays the dates in an input field with id="datepicker" that you can use to get your date. For a client-side calculation, the momentjs library mentionned in other answer if perfect for this job.
fromdate = $('#datepicker').val();
console.log(fromdate);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="text" id="datepicker" class="hasDatepicker" value="2016/14/12">
If you want to calculate server-side, you can pass the value to PHP without reloading page with Ajax:
$('#datepicker').change(function(){
$.ajax({
type: "POST",
url: "datecalc.php",
data: {text:$(this).val()}
});
});
If you want to calculate the age in jQuery, you can use moment.js like this:
moment("05/05/1998", "MM/DD/YYYY").month(0).from(moment().month(0));
// Output = 22 years ago
$(function() {
var dob = $('.dob').val();
$('.dob').on('input', function(e) {
var a = moment($(this).val(), "MM/DD/YYYY").month(0).from(moment().month(0))
console.log(a);
});
var a = moment($('.dob').val(), "MM/DD/YYYY").month(0).from(moment().month(0))
console.log(a);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.5.1/moment.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input class='dob' type='text' value="05/05/1996">
Inside your controller, you can use Carbon's age method like this:
$birthday = Carbon\Carbon::parse('1970-02-01');
$age = $birthday->age;
// Output - (int) 46
See Carbon Docs for reference
Hope this helps!
You need to read the value of the data input field using JQuery or Javascript and then pass the value to your age calculation function.
For example if your date field has id="date-picker", then you can read the date as $("date-picker").val() or document.getElementById("date-picker").value()

Cant quite invalidate/validate dates correctly (arrival date) ?

This is my html code with a snippet of just the code I am trying to use to invalidate/validate date entries with hopefully all of the corresponding and necessary variables declared.
<html>
<head>
<title> Booking Page </title>
<script>
function Booking(){
var departuredate = document.getElementById("departdate").value; //departure date selected by user
var arrivaldate = document.getElementById("arrivedate").value; //arrival date selected by user
departuredate = new Date(departuredate);
arrivaldate = new Date(arrivaldate);
CurrentDate = new Date(); //todays date
month = '' + (arrivaldate.getMonth() + 1),
day = '' + arrivaldate.getDate(),
year = arrivaldate.getFullYear();
var adate = [day, month, year].join('/');
alert(adate);
the adate is for the arrival date only. I plan to just copy and adjust the code across once it is correct for the departure date. Currently the code seems to invalidate all entries, not allowing completely valid entries to be validated.
var re = /[0-9]{2}\/[0-9]{2}\/[0-9]{4}/;
if (!adate.match(re))
{
document.getElementById("temp").innerHTML = "Incorrect format"
document.MyForm.arrivedate.focus();
document.getElementById("arrivedate").style.border='1px solid red';
return false;
}
else
{
// if none of the above situaton's occur then the input is true and validated
alert('Dates are validated');
return true;
}
}
</script>
</head>
<body>
<H1> Booking Form </H1>
<Form action="testpage.py" method="POST" name="MyForm" onsubmit="return Booking()">
<p>Departure Date:</p>
<input type=date name="departdate" id="departdate" >
<p>Arrival Date:</p>
<input type=date name="arrivedate" id="arrivedate">
<input type=submit value="Find flights">
</Form>
</body>
</html>
You have multiple problems here. First is that the date type for inputs is non-standard, so it won't work in most browsers (IIRC chrome, edge, and iOS safari are the exceptions).
I recommend that you either use a third-party library like jquery-ui-datepicker or use a text input with the validation logic using the html pattern attribute or a js event handler if you have to support desktop safari (which doesn't support the pattern attribute).
Something like <input type="text" pattern="/[0-9]{2}\/[0-9]{2}\/[0-9]{4}/"...
Or if pattern won't work:
var myDateInput = document.getElementById('date-input');
myDateInput.addEventListener('change', function(e) {
if (!(e.target.value.match(dateRegex)) {
//let user know somehow
}
});
You can throttle the handler so that it doesn't fire on successive keystrokes. Also note that even in browsers with the date input type they expect "yyyy-mm-dd" format, so make your regex:
/[0-9]{4}-[0-9]{2}-[0-9]{2}/.

How to save Date & Time in Parse.com using Javascript

I am trying to get the Date and Time from the user and want to submit it to Parse.com. But when I am facing the problem with the following code
What mistake am I doing here?
<div id="main">
<form name="myForm" action="" method="get">
Date: <input type="datetime-local" name="datentime" id="theDate">
<input type="submit" value="Submit" onclick="myFunction()">
</form>
and the javascript code
function myFunction()
{
var TestObject = Parse.Object.extend("TestObject");
var testObject = new TestObject();
var date = new Date();
date = document.getElementById("theDate").value; //document.forms["myForm"] ["datentime"].value; /*new Date();*/
testObject.set("myDate", date);
testObject.save(null, {
success: function(testObject) {
$(".success").show();
},
error: function(testObject, error) {
$(".error").show();
}
});
}
In above line testObject.set("myDate", date); this like is not working.I am not sure how to take the input from the date and give it to the parse.com
where the column name is myDate of type Date
If I try testObject.set("foo","testing...") where foo is column name of type string.It's working properly
Your issue is just with the way that you are creating a date. I would think that it should work, but is it possible that it is creating a string object?
try checking the type of date it should show an object, if it does not, then the date is not a date, but just a string:
console.log(typeof(date));
Also try to log the value:
console.log(document.getElementById("theDate").value);

Categories

Resources