How to add sql query varible into javascript and calculate? - javascript

I'm making a patient system with calculating the age of patient base on their birthday, but i'm getting error when I add it
Javascript:
<script>
var dob = new Date("06/24/2008"); <!-- I wanted to add {{ patient.birth }} into the date part-->
//calculate month difference from current date in time
var month_diff = Date.now() - dob.getTime();
//convert the calculated difference in date format
var age_dt = new Date(month_diff);
//extract year from date
var year = age_dt.getUTCFullYear();
//now calculate the age of the user
var age = Math.abs(year - 1970);
//display the calculated age
document.write("Age of the date entered: " + age + " years");
</script>
And {{ patient.birth }} is the sql query that I wanted to add into the script.

var birthdate = $("#birth").val();
or
var birthdate = "{{ birth }}"
Depending on how the value is being implemented in the jinja.
Let me know which one works for you situation if you could.
I've done this in the past using both of these methods.
note: it's not by accident I'm leaving the "patient." out. This is intentional.
If they are changing the birthdate value on this screen.
Then you need to make an onchange event.
For example:
<head>
<script type="text/javascript" src="https://code.jquery.com/jquery-1.7.1.min.js"></script>
<style>
function makeChange() {
var birthdate = $("birth").val();
}
</style>
</head>
<form method="POST" action="">
<div onchange="makeChange()">
{{ patient.birth }}
</div>
</form>

Argument passed to Date constructor should be in correct format.
In your case patient.birth should be string just like in your example: "06/24/2008".
You can not say like so:
const date = new Date("3 1930");
It prints
Invalid Date
https://www.tutorialspoint.com/javascript/javascript_date_object.htm

Related

Checking difference between two date and display custom message

Hello I have input on registration form and want to retrieve the value of input and compare it with the current date using JavaScript and display message after check age if age less than 18 year and display custom message on the bottom of input.
var dateControl = document.querySelector('input[type="date"]').getFullYear();
var startDate = new Date(document.getElementById('date1').value);
and this is the HTML
<input type="date" name="date" class="form-control" id="date1" value="{{ old('date', date('Y-m-d')) }} " onclick="checkDate()">
<div id="currentdate"></div>
but is give old value after each click.
and the message not displayed
Best regards
Not much code to go from but I think you may need this function anyway to compare the date you receive from the form with the current date and get the difference
function process() {
var today = new Date();
var date = new Date(document.getElementById("date1").value);
var diff = Number((today.getTime() - date.getTime()) / 31536000000).toFixed(0);
if (diff >= 18) {
// Your form submission goes here
console.log("success");
} else {
// your error handeling goes here
console.log("error");
}
}
PS: That this method won't give you the difference in an exact way,
it will just give you the difference between the years.

Broken Delivery Estimate Calculator

I'm hoping someone can help me figure out how to code an app that allows you to select a mailing date with jquery datepicker, select Standard or First-class shipping from a dropdown, and calculate an estimated delivery date window (7-12 Days for Standard, 3-5 Days for First-class).
I had it working when the "Mailing in" [number] "Days" accepted a string input but then it broke when I added code for the datepicker.
I also need to keep weekends & holidays excluded from the shipping calculation.
Here's a link to the full pen: https://codepen.io/allyjfuller/pen/oNXvwJL
$('#calculateShippingEstimate').click(function( event ) {
//Prevent button from 'submitting' and reloading the page
event.preventDefault();
//Capture the mailing date
var $mailingDate = $("#mailingDate").val();
var $postageType = $("#postageType").val();
var $shipStateShippingDuration = eval('data.shipTimes.' + $postageType);
var $totalShippingTime = parseInt($mailingDate) + parseInt($shipStateShippingDuration);
//Create the date
var date = new Date();
var month = date.getMonth()+1;
var day = date.getDate() + parseInt($totalShippingTime);
var year = date.getFullYear();
<form>
<section>
<label>Mailing on</label>
<input id="mailingDate" placeholder="number"></input>
</section>
<section>
<label>Postage:</label>
<select id="postageType">
<option value="Standard">Standard</option>
<option value="FirstClass">First-Class</option>
</select>
</section>
<input class="button" id="calculateShippingEstimate" type="submit" value="Get Estimated Delivery Date"></input>
<div class="results"></div>
</form>
Looking through your code snippet it seems like you're trying to hand roll a lot of features that already exist within the JS Date framework.
Once you get the starting date and the number of days for shipping, you can add those days together to create a final shipping date. From there and within a loop, you may go day by day and check whether the current date index is a weekday or not (using Date.getDay()).
With that you may check for Saturday [6] and Sunday [0] and then add days needed on top of the final date.
I've included my version of the code below with some console debugging but have not added code holidays. Holidays may be checked for using an array or map. Get all the holiday dates for a year and then have the current index check the holiday array/map to see if there are any matches. If there are, add another day to the final date.
The function for addDays is pulled from here. It adds some explanation which I think you'll find helpful.
function addDays(date, days) {
const copy = new Date(Number(date))
copy.setDate(date.getDate() + days)
return copy
}
// FINAL SHIPPING ESTIMATE
$('#calculateShippingEstimate').click(function( event ) {
event.preventDefault();
let mailingDateVal = $("#mailingDate").val();
let shippingDuration = data.shipTimes[$("#postageType").val()];
let mailingDate = new Date(mailingDateVal);
console.log("final Date: " + addDays(mailingDate, shippingDuration));
let finalDate = addDays(mailingDate, shippingDuration)
let mailingDateIndex = new Date(mailingDate);
while(mailingDateIndex <= finalDate) {
console.log("current mailDateIndex: " + mailingDateIndex)
if (mailingDateIndex === finalDate) {
break;
}
// Weekend
console.log(mailingDateIndex.getDay());
if (mailingDateIndex.getDay() == 0 || mailingDateIndex.getDay() == 6) {
console.log("weekend day hit! Adding day to final...")
finalDate = addDays(finalDate, 1);
}
mailingDateIndex = addDays(mailingDateIndex, 1);
}
});

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.

WebForm Date Field

I am creating a form and not finding how to populate a date field with the calendar date. The form should populate the date when a new form is created. I have the following code:
<div>
<label><b>Request Initiation Date</b></label><br />
<input type="date" id="RequestDate">
<script>
(function() {
var date = new Date().toISOString().substring(0, 10);
var field = document.querySelector('#Requestate');
field.value = date;
console.log(field.value);
});
</script>
</div>
You have two issues. Firstly, in
document.querySelector('#Requestate')
you have mistyped the element ID, it should be
document.querySelector('#RequestDate')
--------------------------------^
Secondly, you aren't calling the function, so the last line should be:
}());
-----^^
The full code:
<div>
<label><b>Request Initiation Date</b></label><br />
<input type="date" id="RequestDate">
<script>
(function() {
var date = new Date().toISOString().substring(0, 10);
var field = document.querySelector('#RequestDate');
field.value = date;
console.log(field.value);
}());
</script>
</div>
Of course you can write it in less code, but you should consider readability and maintainability before doing that.
You can use the below-given js -
document.getElementById("RequestDate").valueAsDate = new Date()
The new Date() fn will get the current date and assign it to the target input[type=date] control.

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()

Categories

Resources