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>
Related
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>
What i am trying to do now is have separate calculation when a radio button is highlighted for particular fields... in this case if the radio button is highlightedior "yearly" i want the user input of the text field to be calculated maintFees * 1 = x variable and show that output in maintTimesTwelve.
if not highlighted for "yearly" i want it to be calculated by maintFees * 12. and shown in maintTimesTwelve.
js fiddle:https://jsfiddle.net/ryx4qt0d/
here is the copy of my code
// start of variables
function yearlyPayment(){
var monthlyPayment = parseInt(document.getElementById("monthlyPayment").value);
var maintFees = parseInt(document.getElementById("maintFees").value);
var memFees = parseInt(document.getElementById("memFees").value);
var exchFees = parseInt(document.getElementById("exchFees").value);
var result = (monthlyPayment?monthlyPayment:0) + (maintFees?maintFees:0) + (memFees?memFees:0) + (exchFees?exchFees:0);
document.getElementById("txtResult").value = result;}
//first function after submission
function mpTwelve(){
var monPay = parseInt(document.getElementById("monthlyPayment").value);
var monTwe = monPay * 12;
document.getElementById("mpTimesTwelve").value = monTwe;}
// sencond function
function maintTwelve(){
var maintPay = parseInt(document.getElementById("maintFees").value);
var maintTwe = maintPay * 12;
var x = maintPay * 1;
if (document.getElementByClass("year").checked){
document.getElementById("mantTimesTwelve").value = x;
}
else{
document.getElementById("maintTimesTwelve").value = maintTwe;}
}
// third function
function yearlyTen(){
var yearPay = parseInt(document.getElementById("txtResult").value);
var yearTen = yearPay * 120;
document.getElementById("totalYearly").value = yearTen;}
//4th function
function yearlyTenMaint(){
var tenMain = parseInt(document.getElementById("maintTimesTwelve").value);
var tenMainTen = (tenMain * 120) * .5;
document.getElementById("maintTenYear").value = tenMainTen;}
//fifth function
function totalMeEx(){
var meEx = parseInt(document.getElementById("memFees").value);
var exMe = parseInt(document.getElementById("exchFees").value);
var totalExMe = (meEx + exMe) * 120;
document.getElementById("totalMemDues").value = totalExMe;
}
<div>
<p>
Monthly payment:<br>
<input type="text" id="monthlyPayment" class="input"/><br>
Maintenance fees:<br>
<input style="margin-left: 79px" type="text" id="maintFees" class="input"/>
<input type="radio" id="year" name="year" class="year">
<label for="year"> Yearly </label><br>
Membership dues:<br><br>
<input type="text" id="memFees" class="input"/><br>
xchange Fees<br>
<input type="text" id="exchFees" class="input"/><br>
<br>
Annual timeshare vacation cost:<br>
<input type="text" id="txtResult"/><br>
Monthly payment x 12<br>
<input type="text" id="mpTimesTwelve"/><br>
Maintenance fees x 12<br>
<input type="text" id="maintTimesTwelve"/><br>
Total yearly payment x10 years:<br>
<input type="text" id="totalYearly"/><br>
Yearly Mainteneance over 10 years w/ 5% increase:<br>
<input type="text" id="maintTenYear"/><br>
Membership Dues + Exchange Fees x 10 years:<br>
<input type="text" id="totalMemDues"/><br>
<button onclick="yearlyPayment(); mpTwelve(); maintTwelve();yearlyTen(); yearlyTenMaint();totalMeEx();">calculate</button><br>
</p></div>
if (document.getElementByClass("year").checked){ should be if (document.getElementsByClassName("year")[0].checked){ because getElementsByClassName() returns a collection. Can be simplified by using if (document.querySelector(".year").checked){
You had a typo here: document.getElementById("mantTimesTwelve") mant should be maint
Please: Check the console everytime a script doesn't run, it's so easy to find this kind of errors.
// start of variables
function yearlyPayment(){
var monthlyPayment = parseInt(document.getElementById("monthlyPayment").value);
var maintFees = parseInt(document.getElementById("maintFees").value);
var memFees = parseInt(document.getElementById("memFees").value);
var exchFees = parseInt(document.getElementById("exchFees").value);
var result = (monthlyPayment?monthlyPayment:0) + (maintFees?maintFees:0) + (memFees?memFees:0) + (exchFees?exchFees:0);
document.getElementById("txtResult").value = result;}
//first function after submission
function mpTwelve(){
var monPay = parseInt(document.getElementById("monthlyPayment").value);
var monTwe = monPay * 12;
document.getElementById("mpTimesTwelve").value = monTwe;}
// sencond function
function maintTwelve(){
var maintPay = parseInt(document.getElementById("maintFees").value);
var maintTwe = maintPay * 12;
var x = maintPay * 1;
if (document.getElementsByClassName("year")[0].checked){
document.getElementById("maintTimesTwelve").value = x;
}
else{
document.getElementById("maintTimesTwelve").value = maintTwe;
}
}
// third function
function yearlyTen(){
var yearPay = parseInt(document.getElementById("txtResult").value);
var yearTen = yearPay * 120;
document.getElementById("totalYearly").value = yearTen;}
//4th function
function yearlyTenMaint(){
var tenMain = parseInt(document.getElementById("maintTimesTwelve").value);
var tenMainTen = (tenMain * 120) * .5;
document.getElementById("maintTenYear").value = tenMainTen;}
//fifth function
function totalMeEx(){
var meEx = parseInt(document.getElementById("memFees").value);
var exMe = parseInt(document.getElementById("exchFees").value);
var totalExMe = (meEx + exMe) * 120;
document.getElementById("totalMemDues").value = totalExMe;
}
<div>
<p>
Monthly payment:<br>
<input type="text" id="monthlyPayment" class="input"/><br>
Maintenance fees:<br>
<input style="margin-left: 79px" type="text" id="maintFees" class="input"/>
<input type="radio" id="year" name="year" class="year">
<label for="year"> Yearly </label><br>
Membership dues:<br><br>
<input type="text" id="memFees" class="input"/><br>
xchange Fees<br>
<input type="text" id="exchFees" class="input"/><br>
<br>
Annual timeshare vacation cost:<br>
<input type="text" id="txtResult"/><br>
Monthly payment x 12<br>
<input type="text" id="mpTimesTwelve"/><br>
Maintenance fees x 12<br>
<input type="text" id="maintTimesTwelve"/><br>
Total yearly payment x10 years:<br>
<input type="text" id="totalYearly"/><br>
Yearly Mainteneance over 10 years w/ 5% increase:<br>
<input type="text" id="maintTenYear"/><br>
Membership Dues + Exchange Fees x 10 years:<br>
<input type="text" id="totalMemDues"/><br>
<button onclick="yearlyPayment(); mpTwelve(); maintTwelve();yearlyTen(); yearlyTenMaint();totalMeEx();">calculate</button><br>
</p></div>
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>
As I mention in the title I have three input in HTML:
<input type="number" name="time" id="time">
<input type="time" name="hour_start" id="hour_start">
<input type="time" name="hour_final" id="hour_final">
and JS:
<script>
$("#time").change(function () {
var time = $('#time').val();
var start = $('#hour_start').val();
var convert = Math.floor(time/60);
var final = start + convert;
$('#hour_final').val(final);
});
</script>
The calculation is done without using a button.
Enter image description here
Javascript answser ( as you asking) :
const myForm = document.querySelector('#my-Form')
, z2 = v=>('00'+v).slice(-2) // like padStart(2.'0')
myForm.time.oninput=_=>
{
let inDate = myForm.hour_start.valueAsDate
, h_UTC = inDate.getUTCHours()
, m_UTC = inDate.getUTCMinutes()
, nTim = (h_UTC * 60) + m_UTC + myForm.time.valueAsNumber
h_UTC = Math.trunc(nTim/60) % 24
m_UTC = nTim % 60
inDate.setUTCHours(h_UTC)
inDate.setUTCMinutes(m_UTC)
myForm.hour_final.valueAsDate = inDate
}
myForm.onsubmit=e=>
{
e.prventdefault() // just for test
}
<form action="xxx" id="my-Form">
<input type="number" name="time" value="0" min="0" max="2000">
<input type="time" name="hour_start" value="13:30">
<input type="time" name="hour_final" value="13:30">
</form>
I'm trying to use validation on input field for Employee salary
calculation form by using javascript.
The calculation code works fine, however it can't validate input field before proceeding with calculation.
Here the code.
function validateForm() {
var x = document.forms["myForm"]["employeename"]["employeeno"].value;
if (x == "") {
alert("Please fill up Empty field");
return false;
}
}
function paySalary() {
var employeeName = document.getElementById("employeename").value;
var employeeNo = document.getElementById("employeeno").value;
var employeeHours = document.getElementById("hours").value;
var HoursRate = document.getElementById("rate").value;
if (employeeHours <= 40) {
var regtime = HoursRate * employeeHours;
var overtime = 0.00;
var salary = regtime;
} else if (employeeHours > 40) {
var regtime = (HoursRate * 40);
var overtime = ((HoursRate * 1.5) * (employeeHours - 40));
var salary = (regtime + overtime);
}
alert("Paid ammout for " + employeeName + " is for RM " + salary );
}
<body>
<form name="myForm" action="" onsubmit="return checkForm(this)" method="post">
<label>Employee Name :</label>
<input id="employeename" value=""><br>
<label>Employee No :</label>
<input id="employeeno" value=""><br>
<label>Rate of pay :</label>
<input id="rate" value=""><br>
<label>Hours Work :</label>
<input id="hours" value=""><br>
<br>
<button id="submit" onclick="paySalary()" >Submit</button>
</form>
<br>
<br>
</body>
The paySalary() function will be executed as soon as you click the submit button and before the form validation. What you can do is writting the validateForm() inside the paySalary() function. If the conditions pass the test then continue..
function validateForm() {
var x = document.getElementById("employeeno").value;
if (x == "") {
alert("Please fill up Empty field");
return false;
}
return true;
}
function paySalary() {
// If the form is not valid: stop execution
if(!validateForm()) {
return;
}
var employeeName = document.getElementById("employeename").value;
var employeeNo = document.getElementById("employeeno").value;
var employeeHours = document.getElementById("hours").value;
var HoursRate = document.getElementById("rate").value;
if (employeeHours <= 40) {
var regtime = HoursRate * employeeHours;
var overtime = 0.00;
var salary = regtime;
} else if (employeeHours > 40) {
var regtime = (HoursRate * 40);
var overtime = ((HoursRate * 1.5) * (employeeHours - 40));
var salary = (regtime + overtime);
}
alert("Paid ammout for " + employeeName + " is for RM " + salary )
}
<body>
<form name="myForm" action="" onsubmit="return paySalary()" method="post">
<label>Employee Name :</label>
<input id="employeename" value="Bob"><br>
<label>Employee No :</label>
<input id="employeeno"><br>
<label>Rate of pay :</label>
<input id="rate" value="0"><br>
<label>Hours Work :</label>
<input id="hours" value="0"><br>
<br>
<button id="submit">Submit</button>
</form>
<br>
<br>
</body>