Local Variable to Global Variable in JavaScript - javascript

I am developing a web page where the Months will be calculated after entering the Date from the Input Field.
I want to take the value of "diffMonthsGlobe" to another function where this calculated value is going to the database.
But as I have seen few answers in StackOverflow and try to do the same but still in my case it is not possible
var diffMonthsGlobe;
function getValue() {
// Getting Values......
const startDate = document.getElementById("startDate").value;
const endDate = document.getElementById("endDate").value;
// Calculating Time Period.......
const date1 = new Date(endDate);
const date2 = new Date(startDate);
var diffMonth = (date2.getTime() - date1.getTime()) / 1000;
diffMonth /= 60 * 60 * 24 * 7 * 4;
diffMonths = Math.abs(Math.round(diffMonth));
diffMonthsGlobe = diffMonths;
// Printing Values......
console.log(startDate);
console.log(endDate);
console.log(diffMonths + " Months");
return diffMonthsGlobe;
}
getValue();
console.log(diffMonthsGlobe + " Months");
<input type="date" class="form-control" placeholder="Start Date *" name="startDate" id="startDate" required onchange="getValue()" />
<input type="date" class="form-control" placeholder="End Date *" name="endDate" id="endDate" required onchange="getValue()" />

Use a form so the required works
Use the submit event to get the value and send to server
const getValue = function() {
// Getting Values......
const startDate = document.getElementById("startDate").value;
const endDate = document.getElementById("endDate").value;
// Calculating Time Period.......
const date1 = new Date(endDate);
const date2 = new Date(startDate);
var diffMonth = (date2.getTime() - date1.getTime()) / 1000;
diffMonth /= 60 * 60 * 24 * 7 * 4;
diffMonths = Math.abs(Math.round(diffMonth));
diffMonthsGlobe = diffMonths;
// Printing Values......
console.log(startDate);
console.log(endDate);
return diffMonthsGlobe;
}
window.addEventListener("load", function() { // page load
document.getElementById("myForm").addEventListener("submit", function(e) {
e.preventDefault(); // stop submission
const monthDiff = getValue();
console.log(monthDiff + " Months");
// here you can fetch or otherwisde ajax to server
})
})
<form id="myForm">
<input type="date" class="form-control" placeholder="Start Date *" name="startDate" id="startDate" required />
<input type="date" class="form-control" placeholder="End Date *" name="endDate" id="endDate" required />
<input type="submit" />
</form>

Related

How to use js-datepicker in multiple elements using class

I'm using js-datepicker for datepicker on my project. I chose this library because I wanted to use vanilla JS on my application so I won't be using JQuery UI datepickers nor HTML5 input date(for browser compatibility).
The problem is I have multiple inputs that will be datepicker but when I create an instance using their classes the datepicker is only binded on the first element with that class
HTML inputs
<input type="text" class="form-control test-datepickers" id="dp1">
<input type="text" class="form-control test-datepickers" id="dp2">
<input type="text" class="form-control test-datepickers" id="dp3">
<input type="text" class="form-control test-datepickers" id="dp4">
JS instantiation
const test_dp = datepicker('.test-datepickers', {
formatter: (input, date, instance) => {
const offset = date.getTimezoneOffset();
date = new Date(date.getTime() - (offset*60*1000));
input.value = date.toISOString().split('T')[0];
},
showAllDates: true,
minDate: new Date()
});
Please do not suggest to create an instance by id cause I'm creating these inputs dynamically (when the a button is pressed).
You can query for all the elements with the given class and then loop over them to add the datepicker.
const items = document.querySelectorAll(".test-datepickers");
for(let i=0; i<items.length; i++){
const node = items[i];
datepicker(node, {
formatter: (input, date, instance) => {
const offset = date.getTimezoneOffset();
date = new Date(date.getTime() - (offset * 60 * 1000));
input.value = date.toISOString().split('T')[0];
},
showAllDates: true,
minDate: new Date()
});
}
<script src="https://unpkg.com/js-datepicker/dist/datepicker.min.js"></script>
<link rel="stylesheet" href="https://unpkg.com/js-datepicker/dist/datepicker.min.css">
<input type="text" class="form-control test-datepickers" id="dp1">
<input type="text" class="form-control test-datepickers" id="dp2">
<input type="text" class="form-control test-datepickers" id="dp3">
<input type="text" class="form-control test-datepickers" id="dp4">
For dynamic usage,
const items = document.querySelectorAll(".test-datepickers");
document.querySelector("button").addEventListener("click",function(){
let inp = document.createElement("input")
inp.setAttribute("type","text");
document.body.appendChild(inp);
datepicker(inp, {
formatter: (input, date, instance) => {
const offset = date.getTimezoneOffset();
date = new Date(date.getTime() - (offset * 60 * 1000));
input.value = date.toISOString().split('T')[0];
},
showAllDates: true,
minDate: new Date()
});
})
for(let i=0; i<items.length; i++){
const node = items[i];
datepicker(node, {
formatter: (input, date, instance) => {
const offset = date.getTimezoneOffset();
date = new Date(date.getTime() - (offset * 60 * 1000));
input.value = date.toISOString().split('T')[0];
},
showAllDates: true,
minDate: new Date()
});
}
<script src="https://unpkg.com/js-datepicker/dist/datepicker.min.js"></script>
<link rel="stylesheet" href="https://unpkg.com/js-datepicker/dist/datepicker.min.css">
<button>Add date</button>
<br/>
<input type="text" class="form-control test-datepickers" id="dp1">
<input type="text" class="form-control test-datepickers" id="dp2">
<input type="text" class="form-control test-datepickers" id="dp3">
<input type="text" class="form-control test-datepickers" id="dp4">

Set Datepicker MAX date From another Datepicker Value

So i have this simple date picker
<input asp-for="D_From" type="date" onchange="myFunction()" id="dfrom" min="1945-01-01" max="9999-12-31" class="form-control">
<input asp-for="D_To" type="date" id="dto" class="form-control">
this is my current script
<script type="text/javascript">
function myFunction() {
var x = document.getElementById("dfrom").value;
document.getElementById("dto").min = x;
}
</script>
i want to set the max to the picked date in dfrom
ex : if dfrom date was 2020-01-01 i want the dto max 2020-01-31
You could achieve this with the following script.
<input asp-for="D_From" type="date" onchange="myFunction()" id="dfrom" min="1945-01-01" max="9999-12-31" class="form-control">
<input asp-for="D_To" type="date" id="dto" class="form-control">
<script type="text/javascript">
function myFunction() {
var x = document.getElementById("dfrom").value;
document.getElementById("dto").min = x;
var month = x.split('-')[1]; // chosen month
var d = new Date(2008, month, 0);
var lastDay = d.getDate(); // last day of month
var maxDate = x.split('-')[0] + '-' + x.split('-')[1] + '-' + lastDay;
document.getElementById("dto").max = maxDate;
}
</script>
There's alot of room for improvements but I hope you get the general idea.

How to create a condition with two inputs with date?

can you please help me with someone with the data boxes?
I have two data boxes.
I would need to somehow create a condition in PHP or JavaScript so that the date2 field is always higher than date1.
If the condition were violated, the date2 field would be automatically set to the same date as in date1.
<div class="form-group">
<input type="date" class="form-control" onchange="vypocet();ubytko_single();ubytko_double();" onkeydown="return false" id="datumprijezdu" name="datumprijezdu" min="<?php echo (new DateTime())->format('Y-m-d'); ?>" value="<?php echo (new DateTime())->format('Y-m-d'); ?>">
<label class="form-control-placeholder" for="datumprijezdu">Datum příjezdu</label>
</div>
<div class="form-group">
<input type="date" class="form-control" onchange="DateCheck();vypocet();ubytko_single();ubytko_double();" onkeydown="return false" id="datumodjezdu" name="datumodjezdu" value="<?php echo (new DateTime('tomorrow'))->format('Y-m-d'); ?>" min="<?php echo (new DateTime('tomorrow'))->format('Y-m-d'); ?>">
<label class="form-control-placeholder" for="datumodjezdu">Datum odjezdu</label>
</div>
JS
function vypocet() {
const _MS_PER_DAY = 1000 * 60 * 60 * 24;
// a and b are javascript Date objects
function dateDiffInDays(a, b) {
// Discard the time and time-zone information.
const utc1 = Date.UTC(a.getFullYear(), a.getMonth(), a.getDate());
const utc2 = Date.UTC(b.getFullYear(), b.getMonth(), b.getDate());
return Math.floor((utc2 - utc1) / _MS_PER_DAY);
}
// test it
var x = document.getElementById("datumprijezdu");
var datumprijezdu = x.value;
var y = document.getElementById("datumodjezdu");
var datumodjezdu = y.value;
const a = new Date(datumprijezdu);
b = new Date(datumodjezdu),
pocet_dnu = dateDiffInDays(a, b);
document.getElementById("demo").innerHTML = pocet_dnu;
}
function ubytko_single() {
var ubytko_single_vysledek=0;
var ubytko_single_vysledek = pocet_dnu * 1980;
document.getElementById("ubytko_single_vysledek").innerHTML = ubytko_single_vysledek + "CZK při možnosti single";
}
function ubytko_double() {
var ubytko_double_vysledek=0;
var ubytko_double_vysledek = pocet_dnu * 2260;
document.getElementById("ubytko_double_vysledek").innerHTML = ubytko_double_vysledek + "CZK při možnosti double";
}
I tried searching on the internet, but the scripts found didn't work for me: /
Here is a basic implementation that you can use. :)
If you have details, I can edit my answer.
var date1 = document.getElementById("date1");
var date2 = document.getElementById("date2");
function dateChecker()
{
if (date1.valueAsDate > date2.valueAsDate)
{
date2.value = date1.value;
} else
{
console.log("Dates are fine");
}
}
<input type="date" id="date1">Date 1</input>
<br>
<input type="date" id="date2">Date 2</input>
<br>
<button id="submit" onClick="dateChecker()">Check Dates</button>

Need value of datepicker as part of variable

I need to have the value from a datepicker to a part of a variable. The value from the datepicker must be inserted instead of getAge("02/20/2017") in the this code. the date has to be changed when datepicker is used, then "leeftijd" chages as well of course
function getAge(dateString) {
var birthdate = new Date(dateString).getTime();
var now = new Date().getTime();
var n = (now - birthdate) / 1000;
if (n < 604800) { // less than a month
var week_n = Math.abs(n / 604800).toFixed(2);
return week_n;
} else if (n < 63113852) { // less than 24 months
var month_n = Math.abs(n / 2629743).toFixed(2);
return month_n;
}
}
var age = getAge("02/20/2017");
document.getElementById("age").value = age;
<form name="id">
<input id="age" class="appTextfield" type="text" name="element1" placeholder="age" value="">
<input id="weight" class="appTextfield" type="text" name="element2" placeholder="weight" value="">
<p>Date: <input type="date" id="datepicker" size="30" onchange="getAge()"></p>
</form>
I tried lots of things but i can't get it to work... i must be doing something wrong. Any solutions to get it working?
This code will help you
function getAge(dateString) {
var birthdate = new Date(dateString).getTime();
var now = new Date().getTime();
var n = (now - birthdate) / 1000;
if (n < 604800) { // less than a month
var week_n = Math.abs(n / 604800).toFixed(2);
return week_n;
} else if (n < 63113852) { // less than 24 months
var month_n = Math.abs(n / 2629743).toFixed(2);
return month_n;
}
}
function calculateAge(dateString) {
var age = getAge(dateString);
document.getElementById("age").value = age;
}
<form name="id">
<input id="age" class="appTextfield" type="text" name="element1" placeholder="age" value="">
<input id="weight" class="appTextfield" type="text" name="element2" placeholder="weight" value="">
<p>Date: <input type="date" id="datepicker" size="30" onchange="calculateAge(this.value)"></p>
</form>

Calculate time difference in hh:mm:ss with simple javascript/jquery

I have two input field for the time start and time end and there is another field for the difference which is the Call Duration. I want the result on the field to be in this format = 00:21:03
<div class="inline_divider">
<label for="form_qa_startcall" class="qaw_form_label3">Start of Call</label>
<input type="text" id="form_qa_startcall" class="qaw_form_input3" placeholder="eg. 11:36:47 PM" maxlength="11">
</div>
<div class="inline_divider">
<label for="form_qa_endcall" class="qaw_form_label3">End of Call</label>
<input type="text" id="form_qa_endcall" class="qaw_form_input3" placeholder="eg. 11:46:47 PM" maxlength="11">
</div>
<div class="inline_divider">
<label for="form_qa_callduration" class="qaw_form_label3">Call Duration</label>
<input type="text" id="form_qa_callduration" class="qaw_form_input3" placeholder="eg. 00:01:10" maxlength="8">
</div>
I am having a hardtime getting the result due to the "AM/PM" formatting.
I have found a similar question like this but he is using "momentjs". As much as possible, I don't want to use any plugins, just a plain javascript or from jquery will do. This is the code I got working, I am getting the result (0:21:3) but I need it to be two digits for hours, minutes, and seconds (00:21:03).
$("#form_qa_endcall").on('keyup',function(){
var callStart = $('#form_qa_startcall').val();
var callEnd = $('#form_qa_endcall').val();
var timeStart = new Date("01/01/2007 " + callStart);
var timeEnd = new Date("01/01/2007 " + callEnd);
function datediff(fromDate,toDate,interval) {
var second=1000, minute=second*60, hour=minute*60, day=hour*24, week=day*7;
fromDate = new Date(fromDate);
toDate = new Date(toDate);
var timediff = toDate - fromDate;
if (isNaN(timediff)) return NaN;
switch (interval) {
case "years": return toDate.getFullYear() - fromDate.getFullYear();
case "months": return (
( toDate.getFullYear() * 12 + toDate.getMonth() )
-
( fromDate.getFullYear() * 12 + fromDate.getMonth() )
);
case "weeks" : return Math.floor(timediff / week);
case "days" : return Math.floor(timediff / day);
case "hours" : return Math.floor(timediff / hour);
case "minutes": return Math.floor(timediff / minute);
case "seconds": return Math.floor(timediff / second);
default: return undefined;
}
}
var seco = datediff(timeStart, timeEnd, 'seconds') % 60;
var minu = datediff(timeStart, timeEnd, 'minutes') % 60;
var hour = datediff(timeStart, timeEnd, 'hours');
$('#form_qa_callduration').val(hour + ":" + minu + ":" + seco);
});
You could use this code:
function diff(a, b) {
function toTime(a) {
return Date.parse('1970-01-01 ' + a.substr(0,8)) / 1000
+ (a.includes('PM') && (12*60*60));
}
var d = toTime(b) - toTime(a);
return d >= 0 ? new Date(0,0,0,0,0,d).toTimeString().substr(0,8) : '';
}
$('.qaw_form_input3').on('input', function () {
$('#form_qa_callduration').val(
diff($('#form_qa_startcall').val(), $('#form_qa_endcall').val()));
}).click();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="inline_divider">
<label for="form_qa_startcall" class="qaw_form_label3">Start of Call</label>
<input type="text" id="form_qa_startcall" class="qaw_form_input3" placeholder="eg. 11:36:47 PM" maxlength="11">
</div>
<div class="inline_divider">
<label for="form_qa_endcall" class="qaw_form_label3">End of Call</label>
<input type="text" id="form_qa_endcall" class="qaw_form_input3" placeholder="eg. 11:46:47 PM" maxlength="11">
</div>
<div class="inline_divider">
<label for="form_qa_callduration" class="qaw_form_label3">Call Duration</label>
<input type="text" id="form_qa_callduration" class="qaw_form_input3" placeholder="eg. 00:01:10" maxlength="8" readonly>
</div>
As the duration will be updated by changes to the other two input values, it would be a good idea to make the duration input read-only, by adding the readonly attribute.
Assuming you get it as strings, you can roughly do the following.
var str1 = "11:31:51 AM";
var str2 = "11:52:54 AM";
str1 = str1.split(':');
str2 = str2.split(':');
if(str1[2].split(' ').pop() != str2[2].split(' ').pop()) { // one is AM other is PM
str1[0] = parseInt(str1[0])+12;
}
var finalStr = m(str1[0], str2[0])+":"+m(str1[1], str2[1])+":"+m(str1[2], str2[2]);
console.log(finalStr);
function m(n1,n2) {
return Math.abs(parseInt(n1)-parseInt(n2));
}

Categories