JS Question regarding compare date using 2 functions - javascript

Hi I'm very novice at Javascript so apologies for asking naff questions.
This piece of code is returning a Nan when it should retrieve days elapsed.
Is the second function causing the issue?
Here it is:
<body>
<script>
function elapsedTime(date1, date2) {
var start = new Date(date1);
var startMilli = start.getTime();
var end = new Date(date2);
var endMilli = end.getTime();
var elapsed = (endMilli - startMilli);
alert(millisToDaysHoursMinutes(elapsed));
}
function millisToDaysHoursMinutes(millis) {
var seconds = millis / 1000;
var totalMinutes = seconds / 60;
var minutesPerDay = 60 * 24;
var days = totalMinutes / minutesPerDay;
return days;
}
</script>
<form>
Start:<input type="text" name="date1" value="dd/m/year" /><br>
End: <input type="text" name="date2" value="dd/m/year" />
<input type="button" name="button1" onclick="elapsedTime(date1.value, date2.value)" value="Get Elapsed Time" />
</form>
</body>

You need to ensure that the dates entered are valid else you'll get a NaN (Not a Number). Use input type=date and make them required then you can easily check that they're valid before calling your date diff function.
EG:
function elapsedTime(date1, date2) {
var start = new Date(date1);
var startMilli = start.getTime();
var end = new Date(date2);
var endMilli = end.getTime();
var elapsed = (endMilli - startMilli);
alert(millisToDaysHoursMinutes(elapsed));
}
function millisToDaysHoursMinutes(millis) {
var seconds = millis / 1000;
var totalMinutes = seconds / 60;
var minutesPerDay = 60 * 24;
var days = totalMinutes / minutesPerDay;
return days;
}
var date1 = document.querySelector("input[name=date1]"),
date2 = document.querySelector("input[name=date2]"),
button1 = document.querySelector("input[name=button1]");
button1.addEventListener("click", function() {
var date1valid = date1.checkValidity();
var date2valid = date2.checkValidity();
if (date1valid && date2valid) {
elapsedTime(date1.value, date2.value);
} else {
alert("Please provide both dates!");
}
});
<form>
Start:<input type="date" name="date1" required="required" value="dd/m/year" /><br> End: <input type="date" name="date2" required="required" value="dd/m/year" />
<input type="button" name="button1" value="Get Elapsed Time" />
</form>

You should use input type date to make your code work:
<form>
Start:<input type="date" name="date1" /><br>
End: <input type="date" name="date2" />
<input type="button" name="button1" onclick="elapsedTime(date1.value, date2.value)" value="Get Elapsed Time" />
</form>

Related

Returning Value from JavaScript Function into HTML Form Input Value Attribute

I am trying to auto fill a form element with the current date and time in a specific format required by mySQL. My difficulty is auto-filling this value into a form element. So far I have tried using .getElementById("element_id").innherHTML = timestamp
But this does not result in any text filling the form element:
<html>
<head>
<title>Create New Reservation</title>
<script>
function Timestamp()
{
const currentTime = new Date();
var year = currentTime.getFullYear();
var month = currentTime.getMonth();
var day = currentTime.getDate();
var dash = "-";
var space = " ";
var colon = ":";
var hour = currentTime.getHours();
var minutes = currentTime.getMinutes();
var seconds = currentTime.getSeconds();
var timestamp = year.toString().concat(dash, month, dash, day, space, hour, colon, minutes, colon, seconds);
document.getElementById("occurred").innerHTML = timestamp;
}
</script>
</head>
<body onload="Timestamp()">
<h1>Enter Reservation Details</h1>
<form method="POST" action="reservation_process.php">
<fieldset>
<label>Current Time</label><type="text"/>
<input type="text" id="occurred" name="occurred"
<br>
<input type="submit" name="Process" value="Create Entry" />
</form>
</body>
</html>
I have also tried returning the formatted timestamp from the function directly into the value="" attribute, but I suspect my syntax is incorrect and I have not been able to find any HTML documentation on how to do this properly:
<input type="text" id="occurred" name="occurred" value= Timestamp() >
You can use $('#occurred').val(timestamp); instead of document.getElementById("occurred").innerHTML = timestamp; inside your function.
$(element).val(value) sets the value of an input, if you not already have you need to include jQuery to use this.
function Timestamp(){
const currentTime = new Date();
var year = currentTime.getFullYear();
var month = currentTime.getMonth();
var day = currentTime.getDate();
var dash = "-";
var space = " ";
var colon = ":";
var hour = currentTime.getHours();
var minutes = currentTime.getMinutes();
var seconds = currentTime.getSeconds();
var timestamp = year.toString().concat(dash, month, dash, day, space, hour, colon, minutes, colon, seconds);
$('#occurred').val(timestamp);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<html>
<head>
<title>Create New Reservation</title>
<script>
</script>
</head>
<body onload="Timestamp()">
<h1>Enter Reservation Details</h1>
<form method="POST" action="reservation_process.php">
<fieldset>
<label>Current Time</label><type="text"/>
<input type="text" id="occurred" name="occurred"
<br>
<input type="submit" name="Process" value="Create Entry" />
</form>
</body>
</html>

My job quote calculator is returning "X is not a function"

This is a corporate massage job quote calculator.
From the user, we collect:
Start time
End time
Number of clients needing a massage
We then use those variables in conjunction with our business rules of time needed per person and hourly rate for a therapist to determine how many therapists are needed and how much it will cost the client to staff those therapists.
When ran, my console displays an error message "timeStr.split is not a function". I thought there was an issue with the .map() method but I've tried resolving to no avail. I am new to JS and could really use some help, please. Here is the code
HTML
<body>
<label for="starttime">Start Time</label><br>
<input id="starttime" type="time" name="starttime" placeholder="Start time"><br>
<label for="endtime">End Time</label><br>
<input id="endtime" type="time" name="endtime" placeholder="End time"><br>
<label for="clients"># of people needing massage</label><br>
<input id="clients" type="number" name="clients" id=""><br>
<input type="button" value="Submit" id="inputbtn" onclick="calc()">
</body>
JS
/*User Inputs*/
const start = document.getElementById("starttime").value;
const end = document.getElementById("endtime").value;
const people = document.getElementById("clients").value;
let timeStart = new Date("01/02/2020" + start);
let timeEnd = new Date("01/02/2020"+end);
/*constants*/
const rate = 80;
const allot = "00:20:00";
/*Time converter*/
function convTime(timeStr){
arr = timeStr.split(":");
arr = arr.map(Number=> Number);
let theHours = arr[0];
let theMinutes = arr[1]/60;
let timeDec = theHours+theMinutes;
return timeDec;
}
/*formulas*/
const ogTime = timeEnd - timeStart;
const givenTime = convTime(ogTime);
const convAllot = convTime(allot)
const realTime = people*convAllot;
const therapists = realTime/givenTime;
const price = therapists*rate*givenTime;
console.log(price);
Moved declare variables of users inputs into Calc() Method to get the value after user insert it, not only on Document Load
use MomentJs Library to calc diff dates and get Hours, minutes, ...
set inputs default values for DEMO only
/*constants*/
var dateStr = "01/02/2020";
const rate = 80;
const allot = moment(new Date(dateStr)).add("+20m"); // 20 minutes
/*Time converter*/
function convTime(t) {
t = moment(t);
let theHours = t.format('h');
let theMinutes = t.format('mm');
let timeDec = Number(theHours) + Number(theMinutes);
return timeDec;
}
function calc() {
/*User Inputs*/
const start = document.getElementById("starttime").value;
const end = document.getElementById("endtime").value;
const people = document.getElementById("clients").value;
var timeStart = new Date(dateStr + " " + start);
var timeEnd = new Date(dateStr + " " + end);
/*formulas*/
const ogTime = moment(timeEnd).diff(timeStart);
const givenTime = convTime(ogTime);
const convAllot = convTime(allot);
const realTime = people * convAllot;
const therapists = realTime / givenTime;
const price = therapists * rate * givenTime;
console.log(price);
}
calc(); // call it on load -- remove this if you want onclick only
<label for="starttime">Start Time</label><br>
<input id="starttime" type="time" name="starttime" placeholder="Start time" value="07:00"><br>
<label for="endtime">End Time</label><br>
<input id="endtime" type="time" name="endtime" placeholder="End time" value="08:00"><br>
<label for="clients"># of people needing massage</label><br>
<input id="clients" type="number" name="clients" value="1"><br>
<input type="button" value="Submit" id="inputbtn" onclick="calc()">
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>

How to link the function to the HTML button and textfield in JavaScript

I am asked to create a web page that user inserts the age and get some message. If the user is under 21, send to disney.com. I do not know how to send. That is so far what I did. I am not sure the function is correct or not and the HTML button and textfield are not working if I insert the age and click.
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8"/>
<title>check is over 21 or not</title>
<script>
function CalAge(birthDateString) {
var today = new Date();
var birthDate = new Date(birthDateString);
var age = today.getFullYear() - birthDate.getFullYear();
var month = today.getMonth() - birthDate.getMonth();
if (month < 0 || (m === 0 && today.getDate() < birthDate.getDate())) {
age--;
}
return age;
}
if(CalAge() >= 21) {
alert("You are over 21!");
}
if(CalAge() < 21) {
alert("You are under 21!");
}
</script>
</head>
<body >
<input type="text" name="age" size="30" onClick="Calage()" placeholder="Enter your age" />
<br />
<input type="button" onclick="CalAge()" value="SUBMIT Age">
<input type="reset" onclick="CalAge()" value="Reset age">
</html>
If the user is entering their age (not their birthday) then there's no need to calculate age. You could do something like this:
const btnCalcAge = document.querySelector('#btn-calc-age');
const btnReset = document.querySelector('#btn-reset');
const txtAge = document.querySelector('#txt-age');
const MIN_AGE = 21;
btnCalcAge.addEventListener('click', function(e) {
const age = parseInt(txtAge.value, 10);
if (age < MIN_AGE) {
window.location.href = 'http://www.disney.com';
return;
}
console.log('Welcome adult!');
});
btnReset.addEventListener('click', function(e) {
txtAge.value = "";
});
<input id="txt-age" type="text" name="age" size="30" placeholder="Enter your age" />
<br />
<input id="btn-calc-age" type="button" value="SUBMIT Age" />
<input id="btn-reset" type="reset" value="Reset age" />
Here's some code to help you ...
const ageInput = document.querySelector('#age-input');
ageInput.valueAsDate = new Date();
document.querySelector('#Bt-Submit').onclick = function()
{
let Age = new Date( new Date() - ageInput.valueAsDate ).getFullYear() - 1970;
console.log(Age);
if ( Age < 21 ) { document.location.href = "https://disney.com" }
}
document.querySelector('#Bt-Reset').onclick = function()
{
ageInput.valueAsDate = new Date();
}
<label>birth date :
<input type="date" id="age-input" size="30" />
</label>
<br />
<button id="Bt-Submit">SUBMIT Age</button>
<button id="Bt-Reset">Reset Age</button>
I believe you're looking for a redirect technique. This answer perfectly describes how to redirect to another link using JavaScript.
As mentioned in the answer above you could redirect using any of the two options mentioned below:
if(calAge() >= 21) {
window.location.replace("http://www.disney.com");
}
You could use window.location.href as well to achieve the same thing. However, I would strongly recommend reading the answer mentioned above to get a clearer understanding of what is best for your case.

Alert message if date and time is older than a value

I have a form with a date and time field, the date field consists of 3 fields: day, month and year. And time field consists of 2 fields, hour and minute.
I want to show an alert if the date is older than 2 months and 60 hours.
HTML:
<div class="container-date">
<div class="date_day">
<input type="text" maxlength="2" name="input_day" id="input_day" value="">
</div>
<div class="date_month">
<input type="text" maxlength="2" name="input_month" id="input_month" value="">
</div>
<div class="date_year>
<input type="text" maxlength="4" name="input_year" id="input_year" value="">
</div>
</div>
<div class="container-time">
<div class="time_hour>
<input type="text" maxlength="2" name="input_hour" id="input_hour" value="">
</div>
<div class="time_minute">
<input type="text" maxlength="2" name="input_minute" id="input_minute" value="">
</div>
</div>
I can do it with one field only for date, but have now 3 fields that I need.
I tried something like this:
jQuery(document).ready(function($){
var day = $('#input_day');
var month = $('#input_month');
var year = $('#input_year');
var today = new Date();
var currentMonth = today.getMonth();
month.on("input change", function() {
if ((today.getMonth() + 11) - (this + 11) > 4) {
console.log('test');
}
});
});
I'd suggest you to parse the form date, create the comparison date according to the expected period and then return if the formDate is greater than comparisonDate.
Please, let me know if the code below is according to what you expected:
function getFormDate() {
const formYear = $("#input_year").val();
const formMonth = $("#input_month").val() - 1;
const formDay = $("#input_day").val();
const formHour = $("#input_hour").val();
const formMinute = $("#input_minute").val();
return new Date(formYear, formMonth, formDay, formHour, formMinute, 0, 0)
}
function getComparisonDate() {
const today = new Date()
let comparisonDate = new Date()
comparisonDate.setMonth(today.getMonth() - 2)
comparisonDate.setHours(today.getHours() - 60)
return comparisonDate
}
function thereIsMissingValue() {
let anyMissing = false;
const inputs = $(".container-date input, .container-time input")
inputs.each(function () {
if (!$(this).val())
anyMissing = true
});
return anyMissing
}
function displayMessage() {
const formDate = getFormDate()
const comparisonDate = getComparisonDate()
$("#min-allowed-date").text(comparisonDate.toLocaleString())
const isOlderThanComparison = formDate < comparisonDate
$(".older-date").toggle(isOlderThanComparison)
const isInTheFuture = formDate > new Date()
$(".future-date").toggle(isInTheFuture)
const isValidDate = !isOlderThanComparison && !isInTheFuture
$(".valid-date").toggle(isValidDate)
}
function calculate() {
if (thereIsMissingValue()) {
$(".container-date-validation").hide()
return
}
$(".container-date-validation").show()
displayMessage()
}
$('#input_year, #input_month, #input_day, #input_hour, #input_minute').change(function () { calculate(); })
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container-date">
<div class="date_day">
<label>Day</label>
<input type="text" maxlength="2" name="input_day" id="input_day" value="">
</div>
<div class="date_month">
<label>Month</label>
<input type="text" maxlength="2" name="input_month" id="input_month" value="">
</div>
<div class="date_year">
<label>Year</label>
<input type="text" maxlength="4" name="input_year" id="input_year" value="">
</div>
</div>
<div class="container-time">
<div class="time_hour">
<label>Hour</label>
<input type="text" maxlength="2" name="input_hour" id="input_hour" value="">
</div>
<div class="time_minute">
<label>Minute</label>
<input type="text" maxlength="2" name="input_minute" id="input_minute" value="">
</div>
</div>
<div class="container-date-validation" style="display:none">
<p class="older-date" style="display:none">Invalid date. Only dates after
<span id="min-allowed-date"></span> are allowed.
</p>
<p class="future-date" style="display:none">Invalid date. It doesn't allow dates in the future.</p>
<p class="valid-date">This is a valid date</p>
</div>
If you go with milliseconds :
2 months is 5184000000
60 hours is 216000000
total : 5400000000
the wantedDate will be new Date(year, month, day)
var wantedDate = new Date(year,month,day); // will create a date from the inputs
wantedDate.getTime() // will convert to miliseconds
and if you convert the wanted date to milliseconds you can easily find out
wantedDate < Date.now() && wantedDate > (Date.now() - 5400000000)
I really like using Moment.js for things like this. It uses much more human-readable code, like so:
const moment = require('moment'); // assumes you install Moment as a node module
const month = $('#input_month');
const day = $('#input_day');
const year = $('#input_year');
const hour = $('#input_hour');
const minute = $('#input_minute');
const checkDate = () => {
const inputDate = moment(month.val() + '/' + day.val() + '/' + year.val() + ' ' + hour.val() + ':' + minute.val(), "MM-DD-YYYY HH:mm");
const expDate = moment.subtract(2, "months").subtract(60, "hours");
if (moment(inputDate).isBefore(expDate, "minute") {
// do something
}
}
month.on('change', checkDate);
You'll also need to ensure you're getting usable values from your inputs. I suggest using number input types or select menus to restrict input options.

onClick works only once

I input the values, and it works ONCE, which is a problem.
I try to change the numbers, and click Enter again, and it does nothing.
The only way it works again is if I use the scroll to up or down the current value.
var fuel = 2.5;
var mpg = 6;
function Hourly() {
var miles = document.getElementById('miles').value;
var brokerPay = document.getElementById('pay').value;
var gallons = miles / 6;
var hours = miles / 55;
var cost = gallons * fuel;
var net = brokerPay - cost
var hourlyPay = net / hours;
var newHeader = document.getElementById('changeMe');
newHeader.innerHTML = hourlyPay;
}
<h1 id="changeMe">Change me Here</h1>
<input type="number" placeholder="miles" id="miles" required/>
<input type="number" placeholder="Broker Pay" id="pay" required/>
<input type="submit" value="Enter" onclick="Hourly()" />

Categories

Resources