How to subtract X hours to a time field - javascript

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>

Related

How do I grab the value of a date input?

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.

oninput and onchange not working because of bad coding

My code is here. Below is the HTML:
<!DOCTYPE html>
<html>
<title>Electricity and Magnetism Demo</title>
<body>
<p>
<label>Voltage:</label>
<input id="inputVoltage" type="number" oninput="EqualsVoltage()" onchange="EqualsVoltage()"> </p>
<p>
<label>Current:</label>
<input id="inputCurrent" type="number" oninput="EqualsCurrent()" onchange="EqualsCurrent()"> </p>
<p>
<label>Resistance:</label>
<input id="inputResistance" type="number" oninput="EqualsResistance()" onchange="EqualsResistance()"> </p>
<script language="Javascript" type="text/javascript" src="EandM.js"></script>
</body>
</html>
Here is the Javascript:
//Electricity and Magnetism Stuff
function EqualsVoltage() {
var Voltage = document.getElementById("inputVoltage").value;
var Current = document.getElementById("inputCurrent").value;
var Resistance = document.getElementById("inputResistance").value;
document.getElementById("inputVoltage").value = (Current * Resistance);
}
function EqualsCurrent() {
var Voltage = document.getElementById("inputVoltage").value;
var Current = document.getElementById("inputCurrent").value;
var Resistance = document.getElementById("inputResistance").value;
document.getElementById("inputCurrent").value = (Voltage / Resistance);
}
function EqualsResistance() {
var Voltage = document.getElementById("inputVoltage").value;
var Current = document.getElementById("inputCurrent").value;
var Resistance = document.getElementById("inputResistance").value;
document.getElementById("inputResistance").value = (Voltage / Current);
}
I want my calculator to react to both oninput and onchange events when I change a value in the text field.
I've been able to make a converter that converts kilometers to miles when oninput and onchange were functioning; however, I can't figure this out.
When I enter data in the field, it doesn't change the other values. Please help!
The problem: when user edit e.g. voltage in input then calculations at the same time change that input value (the input values and calculated values are usually different). Solution: show output calculations in separate place - not as input values. When you use oninput you don't need to use onchange.
function calc() {
let c = inputCurrent.value;
let r = inputResistance.value;
let v = inputVoltage.value;
msg.innerHTML = `voltage: ${ c*r } <br>`
+ `current: ${ v/r } <br>`
+ `resistance: ${ v/c } <br>`;
}
<p>
<label>Voltage:</label>
<input id="inputVoltage" type="number" oninput="calc()">
</p>
<p>
<label>Current:</label>
<input id="inputCurrent" type="number" oninput="calc()">
</p>
<p>
<label>Resistance:</label>
<input id="inputResistance" type="number" oninput="calc()">
</p>
Calculations:
<div id="msg"></div>
This works. Should have been checking the other text boxes not the current one. It will keep changing the fields as the user increases or decreases the value.
<!DOCTYPE html>
<html>
<title>Electricity and Magnetism Demo</title>
<head>
<script type="text/javascript">
function EqualsVoltage() {
var Voltage = document.getElementById("inputVoltage").value;
var Current = document.getElementById("inputCurrent").value;
var Resistance = document.getElementById("inputResistance").value;
if(Resistance != "0" && Current != "0" ){
document.getElementById("inputVoltage").value = (Current * Resistance);
}
}
function EqualsCurrent() {
var Voltage = document.getElementById("inputVoltage").value;
var Current = document.getElementById("inputCurrent").value;
var Resistance = document.getElementById("inputResistance").value;
if(Voltage != "0" && Resistance != "0" ){
document.getElementById("inputCurrent").value = (Voltage / Resistance);
}
}
function EqualsResistance() {
var Voltage = document.getElementById("inputVoltage").value;
var Current = document.getElementById("inputCurrent").value;
var Resistance = document.getElementById("inputResistance").value;
if(Voltage != "0" && Current != "0" ){
document.getElementById("inputResistance").value = (Voltage / Current);
}
}
</script>
</head>
<body>
<p>
<label>Voltage:</label>
<input id="inputVoltage" type="number" oninput="EqualsResistance(); EqualsCurrent()" value="0"> </p>
<p>
<label>Current:</label>
<input id="inputCurrent" type="number" oninput="EqualsVoltage(); EqualsResistance()" value="0"> </p>
<p>
<label>Resistance:</label>
<input id="inputResistance" type="number" oninput="EqualsCurrent();EqualsVoltage()" value="0"> </p>
</body>
</html>
There is already a great answer you can take, but I wanted to provide you an alternative. It's up to you which one fits better to your needs.
This solution provides an alternative for the user to decide when to calculate the values. This can avoid unexpected values as Infinity, 0, etc..
For this, you could give a button to every element in order to let the user click the one he wants the result for. This will update the value to the input box where he presses the button. The button would look like this:
<p>
<label>Resistance:</label>
<input id="inputResistance" type="number">
<button id="calcResistance"><!-- Add this to every input -->
Calc
</button>
</p>
And your JavaScript code will look like this:
function updateValues(e) {
let changed = e.target.id,
Voltage = Number(document.getElementById('inputVoltage').value),
Current = Number(document.getElementById("inputCurrent").value),
Resistance = Number(document.getElementById('inputResistance').value);
switch(changed){
case "calcResistance":
document.getElementById("inputResistance").value = (Voltage / Current);
break;
case "calcVoltage":
document.getElementById("inputVoltage").value = (Current * Resistance);
break;
case "calcCurrent":
document.getElementById("inputCurrent").value = Voltage / Resistance;
break;
}
}
document.querySelectorAll("button").forEach(b=>b.addEventListener("click",updateValues));
I hope this gives you another way to achieve what you want.
Here is a fiddle of what I am talking about:
function updateValues(e) {
let changed = e.target.id,
Voltage = Number(document.getElementById('inputVoltage').value),
Current = Number(document.getElementById("inputCurrent").value),
Resistance = Number(document.getElementById('inputResistance').value);
switch(changed){
case "calcResistance":
document.getElementById("inputResistance").value = (Voltage / Current);
break;
case "calcVoltage":
document.getElementById("inputVoltage").value = (Current * Resistance);
break;
case "calcCurrent":
document.getElementById("inputCurrent").value = Voltage / Resistance;
break;
}
}
document.querySelectorAll("button").forEach(b=>b.addEventListener("click",updateValues));
<p>
<label>Voltage:</label>
<input id="inputVoltage" type="number">
<button id="calcVoltage">
Calc
</button></p>
<p>
<label>Current:</label>
<input id="inputCurrent" type="number">
<button id="calcCurrent">
Calc
</button></p>
<p>
<label>Resistance:</label>
<input id="inputResistance" type="number">
<button id="calcResistance">
Calc
</button></p>
I would recommend using onkeyup instead of onchange and oninput. [edit] Wont work with the buttons, however.
I'm guessing the workflow is "When I enter something two number fields, the third one is calculated".
But what happens then if all three text fields are filled in?
If you filled in voltage, current, and resistance, and then change voltage again, should current or resistance change?
You need to think about workflow before you do any coding, and that's why the code is wrong.

get the quotient of two textbox which has an onChange event

I get the sum of ua and ub and display on tu textbox. I multiplied the ua
and ga textbox and display on uu textbox as well as the ub ang gb . Get
the sum of uu and a and display on tt textbox. I want to get the quotient
of tt and tu and display on gpa textbox but it doesnt work. Please help.
Thanks in advance.
function sum(){
var ua = document.getElementById('ua').value;
var ub = document.getElementById('ub').value;
var result = parseInt(ua) + parseInt(ub);
if (!isNaN(result)) {
document.getElementById('tu').value = result;
document.getElementById('tu').dispatchEvent(new Event('change'));
}
}
function suma(){
var ua = document.getElementById('ua').value;
var ga = document.getElementById('ga').value;
var result = parseInt(ua) * parseInt(ga);
if (!isNaN(result)) {
document.getElementById('uu').value = result;
document.getElementById('uu').dispatchEvent(new Event('change'));
}
}
function sumb(){
var ub = document.getElementById('ub').value;
var gb = document.getElementById('gb').value;
var result = parseInt(ub) * parseInt(gb);
if (!isNaN(result)) {
document.getElementById('a').value = result;
document.getElementById('a').dispatchEvent(new Event('change'));
}
}
function s(){
var uu = document.getElementById('uu').value;
var a = document.getElementById('a').value;
var result = parseInt(uu) + parseInt(a);
if (!isNaN(result)) {
document.getElementById('tt').value = result;
document.getElementById('tt').dispatchEvent(new Event('change'));
}
}
function g(){
var tt = document.getElementById('tt').value;
var tu = document.getElementById('tu').value;
var result = parseFloat(tt) / parseFloat(tu);
if (!isNaN(result)) {
document.getElementById('gpa').value = result;
}
}
<input type="text" id="ua" name="ua" size="7" onkeyup="sum();">
<input type="text" id="ga" name="ga" size="7" onkeyup="suma();">
<input type="text" id="uu" name="uu" size="7" onchange="s();"/>
<input type="text" id="ub" name="ub" size="7" onkeyup="sum();">
<input type="text" id="ga" name="ga" size="7" onkeyup="sumb();">
<input type="text" id="a" name="a" size="7" onchange="s();"/>
<input type="text" id="tu" name="tu" onchange="g();"/>
<input type="text" id="tt" name="tt" onchange="g();"/>
<label>GPA</label>
<input type="text" id="gpa" />
As far as I can tell, everything in your code works (after your edit), except that you want to get the element with the ID gb in the function sumb, but the element doesn't exist. As you have it now, your code displays the result of the value of tt (second in the HTML) divided by the value of tu (first in the HTML).
That said, I'm still not sure what you mean when you say "it's not working". The only thing I could think of is that you have to take away the focus from the tu or tt input element in order to make the gpa element display the result, because you used onchange instead of onkeyup.
As others have pointed out and as I also want to emphasize is that you should try to give your variables meaningful names. When you look at your code in three years, do you think you will still know what "gpa" and "uu" is?
In the following snippet, I only copied the <input>s that are relevant for the division. I use addEventListener instead of inline event listeners (onkeyup="sumb();") and made it more readable:
var dividendElement = document.getElementById('dividend');
var divisorElement = document.getElementById('divisor');
var resultElement = document.getElementById('result');
function updateQuotient () {
var result = parseFloat(dividendElement.value) / parseFloat(divisorElement.value);
if (!isNaN(result)) {
resultElement.value = result;
}
}
dividendElement.addEventListener('keyup', updateQuotient);
divisorElement.addEventListener('keyup', updateQuotient);
<input type="text" id="dividend">
/
<input type="text" id="divisor"> <!-- <input> elements don't need a closing tag! -->
=
<input type="text" id="result">

Simple JavaScript function returns function and not value

I'm just starting out and I'm trying to build a simple calculation function that will display the result of 2 numbers on a page. When the submit button is hit the output is the function and not the value. Where have I gone wrong?
HTML
<div id="input">
<form id="start">
<input id="price" type="number" placeholder="What is the starting price?" value="10">
<input id="tax" type="number" value="0.08" step="0.005">
</form>
<button type="button" form="start" value="submit" onClick="total()">Submit</button>
</div>
<div id="test">Test</div>
JS
<script>
'use strict';
var total = function() {
var price = function() {
parseFloat(document.getElementById("price"));
}
var tax = function() {
parseFloat(document.getElementById("tax"));
}
var final = function() {
final = price * tax;
final = total
}
document.getElementById("output").innerHTML = final;
};
</script>
You have several issues with your javascript. Let's break them down one by one:
var price = function() {
parseFloat(document.getElementById("price"));
}
document.getElementById returns an element. parseFloat would try to calculate the element, and not the value in this case (Which would always be NaN or Not a Number). You want the value of this element, so using .value will return the value. Furthermore, you're not actually doing anything with the value. (You should use return to return the float found, or set it to another variable.)
var final = function() {
final = price * tax;
final = total
}
price and tax are both functions in this case. You can't simply multiply them to get your desired result. Using var total = price() * tax(); will set the variable total to the float returned from price() and tax() now. Returning this value to the function will fix the next line:
document.getElementById("output").innerHTML = final;
final here is also a function. You want to call it by using final().
Your final script:
var total = function() {
var price = function() {
return parseFloat(document.getElementById("price").value);
}
var tax = function() {
return parseFloat(document.getElementById("tax").value);
}
var final = function() {
var total = price() * tax();
return total
}
document.getElementById("output").innerHTML = final();
};
<div id="input">
<form id="start">
<input id="price" type="number" placeholder="What is the starting price?" value="10">
<input id="tax" type="number" value="0.08" step="0.005">
</form>
<button type="button" form="start" value="submit" onClick="total()">Submit</button>
</div>
<div id="output">test</div>
You have several issues, you put some code into function without calling them.
Another problem is, you need the value of the input tags.
'use strict';
var total = function() {
var price = parseFloat(document.getElementById("price").value);
// get value ^^^^^^
var tax = parseFloat(document.getElementById("tax").value)
// get value ^^^^^^
// calculate directly the final value
var final = price * tax;
document.getElementById("output").innerHTML = final;
};
<div id="input">
<form id="start">
<input id="price" type="number" placeholder="What is the starting price?" value="10">
<input id="tax" type="number" value="0.08" step="0.005">
</form>
<button type="button" form="start" value="submit" onClick="total()">Submit</button>
<div id="output"></div>
Delete
var final = function() {
final = price * tax;
final = total
}
and instead put
return price * tax;

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