I'm fairly new to javascript, and I'm trying to calculate a value based on other dropdown values.
So there are three dropdowns, one for start time, one for end time and one for break time. There is a 4th input field for the total hours worked. Now, this is a manual field, but I intend to make this field automatically put in a value of the calculated time.
The page is build in wordpress with gravityforms.
Initially, I tried using jQuery hashes to retrieve the values, but that didn't work, so now I've used the Document.getElementById.
function CalcTime()
{
var time1 = Document.getElementById('input_16_2').value();
var time2 = Document.getElementById('input_16_3').value();
var time3 = Document.getElementById('input_16_4').value();
var time1 = time1.split(':');
var time2 = time2.split(':');
var time3 = time3.split(':');
var hours1 = parseInt(time1[0], 10),
hours2 = parseInt(time2[0], 10),
hours3 = parseInt(time3[0], 10),
mins1 = parseInt(time1[1], 10),
mins2 = parseInt(time2[1], 10),
mins3 = parseInt(time3[1], 10);
var hours = hours2 - hours1 - hours3;
var mins = 0;
if(mins2 >= mins1) {
mins = mins2 - mins1 - mins3;
}
else {
mins = (mins2 + 60) - mins1;
hours--;
}
if(mins < 9)
{
mins = '0'+mins;
}
if(hours < 9)
{
hours = '0'+hours;
}
$("#time_duration").val(hours+':'+mins);
Document.getElementById('input_16_5').value = $("#time_duration").val;
}
var showTime = Document.getElementById('input_16_5').value();
Document.getElementById('input_16_4').on("click", CalcTime)
{
showTime.show();
}
When using the console it says I can't use Document.getElementById
as a function, which I understand, however, I don't know what I can do to make it work.
https://jsfiddle.net/3aud5xL4/
now it works (no errors). you're mixing jQuery and vanilla JS in same function, that's why it wasn't working
this is jQuery syntax
$("#time_duration").val(hours + ':' + mins);
this is vanilla JS version
document.getELementById('time_duration').value = hours + ':' + mins
try not to mix those 2 together, or you'll experience some odd results. also convert this
document.getElementById('input_16_5').value = $("#time_duration").val;
into
document.getElementById('input_16_5').value = document.getElementById("time_duration").value;
and one more thing, you define same variables 2 times in your code. this is JS so it won't complain about it too much, but it's a bad practice. so this
var time1 = Document.getElementById('input_16_2').value();
...
var time1 = time1.split(':');
will become this
var time1 = Document.getElementById('input_16_2').value.split(':')