I have a form with these inputs:
<input type="time" name="morningS"/>
<input type="time" name="morningE"/>
<input type="time" name="AfternoonS"/>
<input type="time" name="AfternoonE"/>
<input type="text" name="total"/>
they indicate the start and end time of morning and the afternoon what i want to do is calculate the number of hours in float automatically when i change the value and put it in the total input but i dont know how to do that in javascript, can someone please help? as an example:
08:00 -> 10:00
13:00 -> 17:30
i want the output to be : 6.5
To get data from input you can use:
<input type="time" name="morningS"/>
<input type="time" name="morningE"/>
// morningS
document.getElementsByTagName("input")[0].value
// morningE
document.getElementsByTagName("input")[1].value
To solve your task:
const morningS = "08:00" const morningE = "13:00" const AfternoonS = "10:00" const AfternoonE = "17:30" // Math const diffHoursE = parseInt(AfternoonE.split(":")[0]) - parseInt(morningE.split(":")[0]) const diffHoursS = parseInt(AfternoonS.split(":")[0]) - parseInt(morningS.split(":")[0]) const diffMinutesE = parseInt(AfternoonE.split(":")[1]) - parseInt(morningE.split(":")[1]) const diffMinutesS = parseInt(AfternoonS.split(":")[1]) - parseInt(morningS.split(":")[1]) // Result console.log(result = diffHoursE + diffHoursS + (diffMinutesE + diffMinutesS)/60) //6.5
On change of both inputs, call this function with those elements to get the hours(Untested code. I hope, you get the idea).
function toHours(startTimeInputElement, endTimeInputElement) {
const startDateTime = startTimeInputElement.valueAsDate;
if(startDateTime === null) {
return 'N/A';
}
const endDateTime = endTimeInputElement.valueAsDate;
if(endDateTime === null) {
return 'N/A';
}
const differenceInMilliseconds = endDateTime.getTime() - startDateTime.getTime();
const differenceInHours = (differenceInMilliseconds/(1000 * 60 * 60)).toFixed(1);
return differenceInHours;
}
I used valueAsDate
attribute of the input element. You can check it here . There is also a valueAsNumber
. That could probably be useful. Try that out.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.