How do I grab the value of a date input? - javascript

So basically I want the price of "renting a boat" to change when a specific requirement is met. If the user selects a date that is on a weekday it will grab the value from the input field and the price will be 10$ per hour. If its a Saturday the price will be 15$ per hour, and if its a Sunday the price will be 20$ per hour. The user can rent it up to 10 hours and they will get a total price at the bottom.
All I have at the moment is the HTML code for the input fields, and I don't even know how to begin the JavaScript part. So if anyone can teach how to start that would be greatly appreciated!
<div id="main">
<label for="which_date">Which date do you want to rent?</label>
<input type="date" id="which_date_input" min="2022-05-02">
<button id="submit">Submit</button>
<label for="total_hours">How many hours do you want to rent? (Max 10 hours)</label>
<input type="number" id="total_hours_input" placeholder="0" min="1" max="10">
<p id="result"></p>
I'm sorry if the explanation of what I want is hard to understand, I'm a beginner when it comes to JavaScript.
Thanks

You can try something like this...
function getPrice() {
const whichDate = new Date(document.getElementById("which_date_input").value);
const totalHours = document.getElementById("total_hours_input").value;
let perHour = 10;
if (whichDate.getDay() === 6) {
perHour = 15;
}
if (whichDate.getDay() === 0) {
perHour = 20;
}
document.getElementById("result").innerText = "Total price: $" + totalHours * perHour;
}
<div id="main">
<label for="which_date">Which date do you want the ticket for?</label><br>
<input type="date" id="which_date_input" min="2022-05-02"><br>
<label for="total_hours">How many hours do you want to rent? (Max 10 hours)</label><br>
<input type="number" id="total_hours_input" placeholder="0" min="1" max="10">
<button id="submit" onclick="getPrice()">Submit</button><br>
<p id="result"></p>
</div>

This should give somewhat of a good indication of what you're trying to do.
You can use the input event along with target.value to get the value.
I'm getting value by destructuring: const {value} = target it's similar to target.value.
If you don't want to work with real-time results you can use something like submitButton.addEventListener('submit', ... instead where you set the submitButton via querySelector. but you will still need to read the same target.value from the "hours" input element if you decide to go that way.
// Do something with the results
const someAction = (amount) => {
console.log(`The amount is: £${amount}`)
}
// Get the input element
const totalHoursInput = document.querySelector("#total_hours_input")
// Listen to the input event
totalHoursInput.addEventListener("input", ({
target
}) => {
// Get the day name
const day = new Date().toLocaleString('en-us', {
weekday: 'long'
}).toLocaleLowerCase()
const { value } = target // The input value
// Determine the correct rate
let rate = 10 // Weekday default
if (day === "saturday") {
rate = 15
} else if (day === "sunday") {
rate = 20
}
// do something with the rate x value
someAction(rate * value)
})

<label for="which_date">Which date do you want the ticket for?</label>
<input type="date" id="which_date_input" value="" min="2022-05-02">
<button id="submit" onclick="getDate()">Submit</button>
<p id="result"></p>
<script>
function getDate() {
var x = document.getElementById("which_date_input").value;
document.getElementById("result").innerHTML = x;
}
</script>
now use what condition you want to apply on var X. the pick up date will store in x you can use for your conditions.

Related

How to subtract X hours to a time field

I would like to output in a div the result of a math calculation (subtract). In the specific I have a form with a <input type="time" id="time" name="time"> that let user pick up a time. I would like to display in another div the result of the chosen time - 3 Hours.
So if time chosen is 13:00 I would like to output in the div with class result-1 10:00.
How can I achieve this in JS?
<form action="/action_page.php">
<label>Time:</label>
<input type="time" id="time" name="time">
</form>
<div>
<h1>Dispaly the result of Time - 3 Hours</h1>
<div class="result-1">Result</div>
</div>
What I tried is to replicate what explained here but without result?
When you read data from the <input> element, the math library cannot be used directly because it reads data of type String. So I developed two different solutions that exhibit two different behaviours.
Behaviour-1
The following solution extracts the selected time value based on a time stored in the secondTime array.
const time1 = document.getElementById('time1');
let result = document.getElementById('result');
// If you want to calculate the difference to the fixed time point,
// change the contents of the secondTime array.
let firstTime = []; secondTime = ["03", "00"]
// Function that prints the time difference to the DOM
function calculate() {
if(firstTime.length != 0) {
var hours = firstTime[0] - secondTime[0];
var minutes = firstTime[1] - secondTime[1];
result.innerHTML = "";
result.insertAdjacentHTML("beforeend", `${hours}:${minutes}`);
}
}
// Event fired when <input> element changes
time1.onchange = function() {
firstTime = this.value.split(":");
calculate();
}
#result {
color: red;
}
<form action="/action_page.php">
<label>First Time:</label>
<input type="time" id="time1" name="time">
</form>
<div>
<h1>Dispaly the result of Time - 3 Hours</h1>
<div class="result-1">Result: <span id="result"></span></div>
</div>
Behaviour-2
In the solution below, the value in the <input> element is parsed using the String.prototype.split() method and the time difference is calculated using the calculate() method. Edit the calculate() method for more accurate calculation.
const time1 = document.getElementById('time1');
const time2 = document.getElementById('time2');
let result = document.getElementById('result');
let firstTime = [], secondTime = [];
function calculate() {
if(firstTime.length != 0 && secondTime.length != 0) {
var hours = secondTime[0] - firstTime[0];
result.innerHTML = "";
result.insertAdjacentHTML("beforeend", `${hours} Hours`);
}
}
time1.onchange = function() {
firstTime = this.value.split(":");
calculate();
}
time2.onchange = function() {
secondTime = this.value.split(":");
calculate();
}
#result {
color: red;
}
<form action="/action_page.php">
<label>First Time:</label>
<input type="time" id="time1" name="time">
<label>Second Time:</label>
<input type="time" id="time2" name="time">
</form>
<div>
<h1>Dispaly the result of Time - 3 Hours</h1>
<div class="result-1">Result: <span id="result"></span></div>
</div>
First you should convert string time to integers then you can subtract.
<html>
<script>
function subTime(t,x) {
var t1 = t.split(':');
var x1 = x.split(':');
var tx0 =parseInt(t1[0])- parseInt(x[0]);
var tx1 =parseInt(t1[1])- parseInt(x[1]);
if(tx1<0){tx1+=60;tx0--;}
if(tx0<0){tx0+=12}
if(tx0<10){tx0="0"+tx0}
if(tx1<10){tx1="0"+tx1}
return tx0+":"+tx1;
}
function showTime(e){
var x = "3"+"00";
document.getElementById('res').innerText = subTime(e.target.value, x)
}
</script>
<body>
<input type="time" id="time" onChange='showTime(event);'/>
<div id='res'></div>
</body>
</html>

Age validation using dd/mm/yyyy

I am trying to validate a form I have for age validating using javascript but it doesn't seem to be working.. not sure why.
Basically the date of birth is entered : dd/mm/yyyy and I need to make sure that in order to submit the form the age of the person is between 15 - 80.. I have tried validating this way but doesn't seem to work.
Html
<label>
Date of birth:
<input type="text" name="birth date" id="DOB"
placeholder="dd/mm/yyyy" maxlength="10" pattern="\d{1,2}\/\d{1,2}\/\d{4}"
required="required"/>
</label>
Javascript
var birthDate = document.getElementById("DOB").value;
if (2019 - birthDate < 15 || 2019 - birthDate > 80) {
errMsg =errMsg + "your age must be between 15 and 80\n";
result = false;
}
if (errMsg !== "") {
alert(errMsg);
}
return result;
So, based on your comment, you have a text box as such:
<form>
<input type="text" name="birth date" id="DOB" placeholder="dd/mm/yyyy" maxlength="10" pattern="\d{1,2}\/\d{1,2}\/\d{4}" required="required"/></label>
</form>
Therefore, document.getElementById("DOB").value; will be of the format dd/mm/yyyy.
So, if you are just checking the year, this should do the trick:
onload = function() {
var form = document.getElementById("form"); //assuming this is your form's ID
form.onsubmit = validate;
}
function checkAge() {
var currentYear = new Date().getFullYear();
var birthDate = document.getElementById("DOB").value;
var errMsg = ""; //this line was missing from my code, and preventing it from working.
//turning "dd/mm/yyyy" into an array of the form { "dd", "mm", "yyyy" }, and taking the "yyyy" part
var birthYear = birthDate.split("/")[2];
var age = currentYear - birthYear;
if (age < 15 || age > 80) {
errMsg =errMsg + "your age must be between 15 and 80\n";
result = false;
}
if (errMsg !== "") {
alert(errMsg);
return false; //form won't submit
}
return true; //form will submit
}
As you can see, I also used getFullYear() so that we don't hard code a fixed current year.
But it would probably be cleaner if you use an <input type="date"> element rather than a text box.
document.getElementById("DOB").value is a string, not a date, so you need to convert it. For that there are different methods; one is to convert the string to YYYY-MM-DD format and pass that to the Date constructor.
Moreover, someone's age changes on their birthday, not at the change of a calendar year, so you need a different logic to get their age. One way is to precalculate the date of 15 years ago and of 81 years ago, and test that the entered birthdate lies between these two extremes.
var DOB = document.getElementById("DOB");
var output = document.getElementById("output");
var go = document.getElementById("go");
var fifteenYearsAgo = new Date();
fifteenYearsAgo.setFullYear(fifteenYearsAgo.getFullYear() - 15);
var eightyOneYearsAgo = new Date();
eightyOneYearsAgo.setFullYear(eightyOneYearsAgo.getFullYear() - 81);
// Function returns true when age is OK, false otherwise
function check() {
var birthDate = new Date(DOB.value.replace(/(..)\/(..)\/(....)/, "$3-$2-$1"));
return birthDate <= fifteenYearsAgo && birthDate > eightyOneYearsAgo;
}
go.addEventListener("click", function() {
if (check()) {
output.textContent = "Your age is OK";
} else {
output.textContent = "Your age must be between 15 and 80";
}
});
Birthdate: <input id="DOB"><button id="go">Go</button>
<div id="output"></div>
HTML5
If you are certain about your clients having HTML5 support, then use type="date" for your input element, and dynamically set the min and max attributes of a date typed input element and rely on form validation. If the form gets into the submit handler, you can be sure the validations passed:
var DOB = document.getElementById("DOB");
var form = document.querySelector("form");
var fifteenYearsAgo = new Date();
fifteenYearsAgo.setHours(0, 0, 0, 0);
fifteenYearsAgo.setFullYear(fifteenYearsAgo.getFullYear() - 15);
var eightyOneYearsAgo = new Date();
eightyOneYearsAgo.setHours(0, 0, 0, 0);
eightyOneYearsAgo.setFullYear(eightyOneYearsAgo.getFullYear() - 81);
// Border case: in leap years next condition could be false
if ((new Date()).getDate() === eightyOneYearsAgo.getDate()) {
eightyOneYearsAgo.setDate(eightyOneYearsAgo.getDate()+1);
}
DOB.setAttribute("min", eightyOneYearsAgo.toLocaleString("se").slice(0,10));
DOB.setAttribute("max", fifteenYearsAgo.toLocaleString("se").slice(0,10));
form.addEventListener("submit", function(e) {
alert("Your age is OK");
e.preventDefault();
return false;
});
function validationMessage() {
DOB.setCustomValidity("");
const msg = DOB.checkValidity() ? ""
: DOB.validity.valueMissing ? "This field is required"
: DOB.validity.rangeOverflow ? "You must be at least 15"
: DOB.validity.rangeUnderflow ? "You must be at most 80"
: "Enter a valid date"
DOB.setCustomValidity(msg);
}
DOB.addEventListener("input", validationMessage);
validationMessage();
<form>
<label>
Date of birth:
<input type="date" name="birth date" id="DOB" required="required"/>
</label>
<button id="go">Go</button>
</form>
document.getElementById("DOB").value; will give you something like 10/10/2000 and performing arithmetic operations on this string will result in NaN. That must be causing an issue.
Validating date is a more complex than you imagine. There are a lot of things that you need to consider. Use libraries like moment to help you in validating dates.
Edit: Use moment's Difference method to calculate the age.
You can use built in min and max props for input. Try something like this.
<p>Enter a number and click OK:</p>
<input id="id1" type="number" min="15" max="80" required>
<button onclick="myFunction()">OK</button>
<p>If the age is less than 15 or greater than 80, an error message will be
displayed.</p>
<p id="demo"></p>
<script>
function myFunction() {
var inpObj = document.getElementById("id1");
if (!inpObj.checkValidity()) {
document.getElementById("demo").innerHTML = inpObj.validationMessage;
} else {
document.getElementById("demo").innerHTML = "Input OK";
}
}
</script>
Theoretically this should work.
Since you are using pattern and required I assume that you want the error message (if the age is out of range) to be shown to the user in the same way as if the entered date is in the wrong format or is missing. That can be achieved with setCustomValidity.
If you add an event listener of the input event on the DOB-element, you can run a function that checks if the entered age is in rage. It will set the custom error message if the age is out of range, or if the entered date is invalid. Otherwise it let the browser handle the error (if it is missing or of wrong pattern).
function validateDOB(event) {
const minAge = 15, maxAge = 80;
// No custom error message. The broswer will complain if the input isn't in the
// correct form, or if the value is missing since the element has "pattern" and
// and "required".
this.setCustomValidity('');
// Check if there are any other errors
if ( !this.validity.valid ) return;
// Check format of input, and split it into parts
const dobArrayText = this.value.trim().match(/^(\d{1,2})\/(\d{1,2})\/(\d{4})$/);
// dobArrayText is null if not in correct format. Let the broswer handle the error.
if (!dobArrayText) return;
// Decode dobArrayText to numeric values that can be used by the Date constructor.
const dob = {
year : +dobArrayText[3],
month : (+dobArrayText[2]) - 1, // month is zero based in date object.
day : +dobArrayText[1]
}
const dobDate = new Date( dob.year, dob.month, dob.day );
// Check validity of date. The date object will accept 2000-99-99 as input and
// adjust the date to 2008-07-08. To prevent that, and make sure the entered
// dobDate is a valid date, I check if the entered date is the same as the parsed date.
if (
!dobDate
|| dob.year !== dobDate.getFullYear()
|| dob.month !== dobDate.getMonth()
|| dob.day != dobDate.getDate()
) {
this.setCustomValidity('Invalid date');
return;
}
// Calc minAgeDate and maxAgeDate
const minAgeDate = new Date(dob.year + minAge, dob.month, dob.day);
const maxAgeDate = new Date(dob.year + maxAge, dob.month, dob.day);
// Get todays date and set Hours, Minutes, Seconds and Milliseconds to 0.
const todayTimestamp = new Date().setHours(0,0,0,0);
// Check validity and set a custom error message if needed.
if ( todayTimestamp < minAgeDate ) {
this.setCustomValidity(`Sorry, you must be older than ${minAge} years old`);
}
else if ( todayTimestamp >= maxAgeDate ) {
this.setCustomValidity(`Sorry, you must be younger than ${maxAge} years old`);
}
}
function formInit() {
document.getElementById('DOB').addEventListener("input", validateDOB);
}
window.addEventListener('DOMContentLoaded', formInit);
<form id="myForm">
<label>
Date of birth:
<input type="text" name="birth_date" id="DOB"
placeholder="dd/mm/yyyy" maxlength="10" pattern="\d{1,2}\/\d{1,2}\/\d{4}"
required="required"/>
</label>
<button type="submit">Submit</button>
</form>

How to pass date id from one jsp to another jsp page

I am calculating the price of a ticket with discount on weekdays and weekends based on the time duration.So, i gave inputs of duration and date using datepicker plugin which is in Above Page. For this i am getting proper result.But i have to create two different jsp pages(date.jsp and cal.jsp).
In 1st jsp page(date.jsp) i am selecting date using datepicker. And in 2nd jsp page(cal.jsp)
I have written a method ->[caluculate(#dateid,#duratiionid)] to calulate the price by taking inputs as time duration.
Here My Question is how shall i pass [#dateid] from 1st jsp page(date.jsp) to 2nd jsp page(cal.jsp)
so that i can pass both the id's in this method->[caluculate(#dateid,#duratiionid)].
<div id="container">
<div id="form">
<form id="book_court">
<div class="fieldset">
<fieldset>
<legend class="visuallyhidden">Booking Details</legend>
<h2>Booking Details</h2>
<p>
<label for="date">Date<br/><span id="dateNote">Firefox does not have a HTML5 datepicker yet.</span></label>
<input type="date" name="date" id="date" min="today" required />
</p>
<p>
<label for="tickets_duration"> Hours</label>
<input type="number" min="1" name="tickets_duration" id="tickets_duration" required />
</p>
<p>
<label>Total Price</label>
<span id="total_price">(enter data first)</span>
</p>
<div id="submit_wrapper">
<input type="submit" id="submit" value="Book Court" />
</div>
</fieldset>
</div>
</form>
</div>
</div>
<script id="worker" type="javascript/worker">
self.onmessage = function msgWorkerHandler(event){
var jsonString = event.data;
var day = jsonString.day;
var tickets_duration = jsonString.tickets_duration;
// set price of each hours as Rs. 200 and 300
var totalPriceOnWeekday = tickets_duration * 200;
var totalPriceOnWeekends=tickets_duration * 300;
// 10% discount if on weekday and 15% on weekends
if(day > 0 && day < 6){
totalPriceOnWeekday = totalPriceOnWeekday - 0.10 * totalPriceOnWeekday;
postMessage("₹ " + totalPriceOnWeekday);
}else if(day == 0 || day == 7){
totalPriceOnWeekends = totalPriceOnWeekends - 0.15 * totalPriceOnWeekday;
postMessage("₹ " + totalPriceOnWeekends);
}
}
</script>
<script>
$(document).ready(function(){
// first check the movies already book
// apply jQuery UI Redmond theme to 'Book Tickets' button
$("#submit").button();
// calculateTotalPrice on keyup or on change of movie/date/tickets
$("#date, #tickets_duration").change(calculateTotalPrice);
// on form submit
$("#book_court").submit(function(event){
// prevent on submit page refresh
event.preventDefault();
// check locally stored data
// clear the form
$( '#book_court' ).each(function(){
this.reset();
});
// reset (enter data first) message
$("#total_price").html("(enter data first)");
// update movies booked list
});
// set minimum date in datepicker as today
var today = new Date().toISOString().split('T')[0];
document.getElementsByName("date")[0].setAttribute('min', today);
});
function calculateTotalPrice(){
if($("#tickets_duration").val() != "" && $("#date").val() != ""){
if(window.Worker){
// create web worker
var blob = new Blob(
[document.querySelector("#worker").textContent],
{type: 'text/javascript'});
var worker = new Worker(window.URL.createObjectURL(blob));
worker.onmessage = function(event){
$("#total_price").html(event.data);
}
worker.onerror = function(errorObject){
$("#total_price").html("Error: " + errorObject.message);
}
var date = new Date($('#date').val());
// get day
var day = date.getDay();
// get number of booked shows
// send JSON data to worker
var jsonData = {'day': day, 'tickets_duration': Number($("#tickets_duration").val())};
worker.postMessage(jsonData);
}
}
}
</script>
If you want to share a value cross-pages, you can use cookie to store the value. Another option is localStorage/sessionStorage if you are using HTML5.
So, in the first page (date.jsp), when user select a date, you can store that selection to cookie, in the second page (cal.jsp) you can read that value from cookie and then do your calculation.
I suppose that you are able to post the date string back to servlet. In the servlet, you are using that date string to check for ticket validity. You just don't know how to check if the date is weekday or weekends. If so you can you the java.util.Calendar for that purpose.
EDITED
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
Date yourDate = formatter.parse(dateInString);
Calendar c = Calendar.getInstance();
c.setTime(yourDate);
int dayOfWeek = c.get(Calendar.DAY_OF_WEEK);

Limiting Text Input Based On Another Text Input

It seems pretty simple but I can't find a good way to do it.
I am doing a research bar which allow users to search something in terms of price mini and price maxi.
So :
I have two text input types (in html of course) "price_mini?" and "price_maxi?".
"Price_mini" cannot be bigger than "price_maxi".
How can I limit the users input of "price_mini" so that if does not allow the user to enter more than the "price_maxi" variable's input and then display an error on save(search) if the mini number is bigger than price_maxi.
Something like this should work, I couldn't get JSFiddle to handle the form to show you a good example and I don't do much in plain javascript now in days so pardon me if there is a small error or two.
HTML
<form name="myForm" onSubmit="submit()" method="post">
<input name="price_mini" type="text">
<input name="price_maxi" type="text">
<input type="submit" value="Submit">
</form>
Javascript
function submit(){
var price_mini = document.forms["myForm"]["price_mini"].value;
var price_maxi = document.forms["myForm"]["price_maxi"].value;
if(Number(price_mini) > Number(price_maxi)){
alert("Minimum price must be less than maximum price!");
}else{
// Your search code here
}
}
Imagine this html
<input id="min" type="text">
<input id="max" type="text">
This should be the correct javascript
var min = document.getElementById("min");
var max = document.getElementById("max");
min.change(function() {
if(Number(this.value) > Number(max.value)) {
this.value = max.value; // replace min with the same max value if it's bigger
}
}
Let's assume that this is your HTML.
<input id="min" type="text">
<input id="max" type="text">
The working JavaScript is this with the behavior if the max field is empty.
var min = document.querySelector('#min');
var max = document.querySelector('#max');
var calculate = function() {
if(max.value == '') return;
if(Number(min.value) > Number(max.value)) {
min.value = max.value;
}
}
min.addEventListener('input', calculate);
max.addEventListener('input', calculate);
You should compare them when they have value (min && max). If you notice that min is higher you can alert to the user or change it automatically to the lowest or to the highest.
$('.calc_input').change( function() {
var min = $('#min').val();
var max = $('#max').val();
if ( (min && max) && min > max ) {
alert('This can not be!');
// $('#min').val() = max;
// $('#max').val() = min;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Min:<input id="min" class="calc_input">
<br>
Max:<input id="max" class="calc_input">

Finding the difference btw two time inputs in javascript

I am developing a webpage to collect information about a person's sleep. Specifically, I am required to find the difference in time between two user inputs which may or may not cross midnight.
I am pretty new to programming in general so am trying to go on using just the skills I am familiar with, though would also like to know if there is an easier way!
The code I have written is as follows:
<script type="text/javascript">
function timeSec() {
var btHours = document.getElementById('bedtimeHours').value;
if (btHours == "") {
btHours = 0;
}
var btMins = document.getElementById('bedtimeMins').value;
if (btMins == "") {
btMins = 0;
}
var btSleepTillMidnight = 0;
var btSecTotal = (btHours*3600) + (btMins*60);
document.getElementById('btSec').value = btSecTotal;
if (btHours > 12) {
btSleepTillMidnight = 24*3600 - btSecTotal;
}
if (btHours <= 12) {
btSleepTillMidnight = ( -Math.abs(btSecTotal));
}
var wtHours = document.getElementById('waketimeHours').value;
if (wtHours == "") {
wtHours = 0;
}
var wtMins = document.getElementById('waketimeMins').value;
if (wtMins == "") {
wtMins = 0;
}
var wtSecTotal = (wtHours*3600) + (wtMins*60);
document.getElementById('wtSec').value = wtSecTotal;
var diffSec = wtSecTotal + btSleepTilMidnight;
document.getElementById('diffSec').value = diffSec;
var diffHours = diffSec/3600;
document.getElementById('diffHours').value = diffHours;
}
</script>
My HTML is as follows, and is pretty much designed to pinpoint errors during development:
<form method="post" action="" name="PSQI" id="PSQI">
Bedtime:
<input type="number" name="bedtimeHours" id="bedtimeHours" min="0" step="1" max="24" value=""> Hours
<input type="number" name="bedtimeMins" id="bedtimeMins" min="0" step="10" max="50" value=""> Minutes
<br>
Waketime:
<input type="number" name="waketimeHours" id="waketimeHours" min="0" step="1" max="24" value=""> Hours
<input type="number" name="waketimeMins" id="waketimeMins" min="0" step="10" max="50" value=""> Minutes
<input type="button" value="Score" onclick="timeSec();">
<br>
btSec: <input type="text" name="btSec" id="btSec" value="">
<br>
wtSec: <input type="text" name="wtSec" id="wtSec" value="">
<br>
diffSec: <input type="text" name="diffSec" id="diffSec" value="">
<br>
diffHours: <input type="text" name="diffHours" id="diffHours" value="">
</form>
Not sure if there's a question here or not, so maybe you're in the wrong place.
I don't know why you're using seconds if the resolution is minutes. Your code seems a bit convoluted, consider the following.
If you pass a reference from the button using this, you can get a reference to the form and save using getElementById, e.g.:
<input type="button" value="Score" onclick="timeSec(this);">
Now in the function you can get the form and access the form controls by name, e.g.
function timeSec(el) {
var form = el.form;
var btSecTotal = form.bedtimeHours.value * 3600 + form.bedtimeMins.value * 60;
var wtSecTotal = form.waketimeHours.value * 3600 + form.waketimeMins.value * 60;
form.btSec.value = btSecTotal;
form.wtSec.value = wtSecTotal;
var secTotal = wtSecTotal - btSecTotal;
if (secTotal < 0) secTotal += 24*60*60;
form.diffSec.value = secTotal;
form.diffHours.value = secondsToHM(secTotal);
}
// Convert seconds to hh:mm format
function secondsToHM(secs) {
function z(n){return (n<10?'0':'')+n}
return z(secs/3600 | 0) + ':' + z((secs%3600)/60 | 0);
}
If someone can't sleep more than 24 hours, get the difference between the bed time and wake time by subtracting wake time from bed time and if it's negative, subtract the difference from 24.
Conversely, if the wake time is earlier than the bed time, add 24hrs to the wake time. To allow for sleep time greater than 24 hours, a slightly different algorithm is required but you will also need something else to tell you that they've slept that long (a "next day" checkbox or similar).
Lastly, don't depend on the browser controlling the values based on the input element attributes. User input should be validated and out–of–range or invalid values should be detected and users asked to fix them. The above doesn't do any of that (it's not hard to do).
Here is a neater way to check the "" zero length input. Also, you don't need to repeat var every time.
var btHours = document.getElementById('bedtimeHours').value || 0,
btMins = document.getElementById('bedtimeMins').value || 0,
btSecTotal = (btHours*3600) + (btMins*60);
an inline if-else
var btSleepTillMidnight = (btHours > 12) ? 24*3600 - btSecTotal : ( -Math.abs(btSecTotal));

Categories

Resources