How can set an input time depending of another input time? - javascript

I'm trying to change link the times input. When I choose a hour in the eventStartTime, I would like to fill, depend of a time passing through the minutesToHours function (in minutes), the eventEndTime (an addition : the eventStartTime + the minutes I've added)
I have tried to do it by myself, but i didn't get any results :
$( document ).ready(function() {
$('#eventStart').on('input', function () {
var convertDuration = minuteToHours(6);
$('#eventEnd').val($(this).val() + moment(convertDuration).format('HH:mm'));
});
});
function minuteToHours(num) {
var hours = Math.floor(num / 60);
var minutes = num % 60;
return hours + ":" + minutes;
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<div class="col-md-4">
<div class="form-group">
<label class="form-label" for="eventStart">Heure début</label>
<input class="form-control" id="eventStart" type="time">
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label class="form-label" for="eventEnd">Heure Fin</label>
<input class="form-control" id="eventEnd" type="time">
</div>
</div>
Thanks for your help !

Related

Time multiplication in HH:MM:SS format

I have three fields like "Duration,Repeat,Complete Duration". User will enter the duration in time format(HH:MM:SS) and they will enter the repeat field value like "5,10,4,9,7 etc". Based on the two fields value the complete duration field should be filled.
I have tried using angular NgModel of both text fields and I multiplied the value with repeat field value. But the conversion was not happened properly.
<div>
<input type="value" [(ngModel)]="user.hrDuration">
<input type="value" [(ngModel)]="user.minDuration">
<input type="value" [(ngModel)]="user.secDuration">
</div>
<div>
<input type="value" [(ngModel)]="user.repeat">
</div>
<div>
<input type="value" [(ngModel)]="user.hrDuration*user.repeat">
<input type="value" [(ngModel)]="user.minDuration*user.repeat">
<input type="value" [(ngModel)]="user.secDuration*user.repeat">
</div>
I have tried like this, but the thing is it is directly multiplied the values, I need to convert and then it should multiply with the repeat field value.
Thanks in Advance!
You should subscribe to the input's input event so you'll know when they're changing:
<div>
<input type="value" [(ngModel)]="user.hrDuration" (input)="updateResult()">
<input type="value" [(ngModel)]="user.minDuration" (input)="updateResult()">
<input type="value" [(ngModel)]="user.secDuration" (input)="updateResult()">
</div>
<div>
<input type="value" [(ngModel)]="user.repeat" (input)="updateResult()">
</div>
<div>
<input type="text" [ngModel]="result.hrDuration">
<input type="text" [ngModel]="result.minDuration">
<input type="text" [ngModel]="result.secDuration">
</div>
and then in the Component have the listening method:
export class AppComponent {
user = {
hrDuration: 1,
minDuration: 1,
secDuration: 1,
repeat: 1
}
result = {
hrDuration: this.user.hrDuration * this.user.repeat,
minDuration: this.user.minDuration * this.user.repeat,
secDuration: this.user.secDuration * this.user.repeat
}
updateResult() {
// do your conversion here
this.result.hrDuration = this.user.hrDuration * this.user.repeat;
this.result.minDuration = this.user.minDuration * this.user.repeat;
this.result.secDuration = this.user.secDuration * this.user.repeat;
}
}
Here is a working stackblitz: https://stackblitz.com/edit/angular-2aukww
I think you should use an onchange event listener and a function that returns the result:
HTML:
<div>
<input type="value" [ngModel]="user.hours" (ngModelChange)="getResult()">
<input type="value" [ngModel]="user.minutes" (ngModelChange)="getResult()">
<input type="value" [ngModel]="user.seconds" (ngModelChange)="getResult()">
</div>
<div>
<input type="value" [ngModel]="user.repeat" (ngModelChange)="getResult()">
</div>
<div>
<input type="value" (ngModel)="user.result" readonly>
</div>
JS:
function getResult() {
if (isNaN($scope.user.hours) ||
isNaN($scope.user.minutes) ||
isNaN($scope.user.seconds) ||
isNaN($scope.user.repeat)) return $scope.user.result = "";
var total = ($scope.user.hours*60*60 + $scope.user.minutes*60 + $scope.user.seconds) * $scope.user.repeat;
var hh = Math.floor(total / (60*60));
if ( hh < 10 ) hh = '0' + hh;
var diff = total % (60*60);
var mm = Math.floor(diff / 60);
if ( mm < 10 ) mm = '0' + mm;
var ss = Math.floor(diff % 60);
if ( ss < 10 ) ss = '0' + ss;
$scope.user.result = hh + ':' + mm+ ':' + ss;
// of course you could also output something like
// 'X hours, Y minutes, Z seconds'
}
Showing the result as a single value will show more clearly the final value, since multiplying each variable (hours, minutes and seconds) by the repeats would be less intuitive.

Face NaN result when calculating time difference with javascript

I'm a newbie and still at the beginner level of PHP, Javascript, Codeigniter. I'm facing an unexpected result when I try to calculate the time difference between two 12 hours format time inputs.
Here is the HTML,JS
function hitungjam() {
var start = new Date($('#inputJammulai'));
var end = new Date($('#inputJamselesai'));
var s = start.toTimeString();
var e = end.toTimeString();
var diff = e - s;
var jam = Math.floor(diff/1000/60/60);
$('#inputSelisih').val(jam);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.0.1/jquery.min.js"></script>
<div class="form-group">
<div class="form-row">
<div class="col-md-4">
<label for="inputJammulai">Start</label>
<!-- <div class="form-label-group"> -->
<input type="time" name="inputJammulai" id="inputJammulai" class="form-control" required="required">
<!-- </div> -->
</div>
<div class="col-md-4">
<label for="inputJamselesai">End</label>
<!-- <div class="form-label-group"> -->
<input type="time" name="inputJamselesai" id="inputJamselesai" onchange="javascript: hitungjam();" class="form-control" required="required">
<!-- </div> -->
</div>
</div>
</div>
RESULT
start 09:00 AM
end 11:30 AM
the result is NaN.
WHAT EXPECTED RESULT
start at 09:00 AM, end at 11:30 AM, the result is 2,5
Oh FYI, before I write down this question I've done a search and tried many solutions given from StackOverflow but doesn't work on my problem. That's why I'm asking now.
Can anyone here help me to find out the solution? Thank you
Here is couple of things First in order to get the value from the input use val() which was missing. Secondly the output from the input is a string, so use parseInt to convert it to number before doing mathematical operations
Using split to get the numbers from the input since the input will be like 9:00 for 9:00AM or 23:30 for 11:30PM.
function hitungjam() {
var start = $('#inputJammulai').val();
var end = $('#inputJamselesai').val();
let diff = toMins(end) - toMins(start);
let jam = `${Math.floor(diff/60)}:${diff%60}`;
$('#inputSelisih').val(jam);
}
function toMins(time) {
let splitTime = time.split(":");
return (parseInt(splitTime[0], 10) * 60) + parseInt(splitTime[1], 10)
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="form-group">
<div class="form-row">
<div class="col-md-4">
<label for="inputJammulai">Start</label>
<!-- <div class="form-label-group"> -->
<input type="time" name="inputJammulai" id="inputJammulai" class="form-control" required="required">
<!-- </div> -->
</div>
<div class="col-md-4">
<label for="inputJamselesai">End</label>
<!-- <div class="form-label-group"> -->
<input type="time" name="inputJamselesai" id="inputJamselesai" onchange="javascript: hitungjam();" class="form-control" required="required">
<!-- </div> -->
</div>
</div>
</div>
<input id='inputSelisih'>
I have done some modifications to your original code so you can get a base working example, I will try to explain some of these:
1) You was not getting the values from your inputs, you need to use .val() for this.
2) You can't make a difference between strings and expect a number as result. Instead of this, I have splited the obtained values from the inputs into hours and minutes. Then we create new Date objects with current time and set the respective hours and minutes to they. Finally, we can use difference within the Date.getTime() of each Date.
3) Math.floor() will return an integer, but you want a number with decimals, so instead of this I use toFixed(1) to get a decimal number (as string) with one digit after the dot.
Base Example:
function hitungjam()
{
var [h1, m1] = $('#inputJammulai').val().split(":");
var [h2, m2] = $('#inputJamselesai').val().split(":");
var start = new Date(), end = new Date();
start.setHours(h1);
start.setMinutes(m1);
end.setHours(h2);
end.setMinutes(m2);
var diff = end.getTime() - start.getTime();
var jam = (diff / 1000.0 / 60 / 60).toFixed(1);
$('#inputSelisih').val(jam);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="time" name="inputJammulai" id="inputJammulai" class="form-control" required="required">
<input type="time" name="inputJamselesai" id="inputJamselesai" onchange="javascript: hitungjam();" class="form-control" required="required">
<label>Difference (hours):<label>
<input type="text" id="inputSelisih">

Range input field return wrong result

Here three time zone range input pakistan, afghanistan and india
here time zone offset in seconds
location offset seconds
pakistan 18000
afghanistan 16200
indian 19800
input range 1 to 24 hour
when I click on any input the range displays all time according to their time zone.
But the problem is when I click on the afghanistan or india input time range it returns wrong time.
when when I click end the input range (mean 24 hour) it return 30 minute behind from the original value
$("#comission div").on("click", "input", function() {
var value = parseInt($(this).val())
var hours1 = Math.floor(value / 60);
var minutes1 = value - (hours1 * 60);
var targetTime = new Date(0);
targetTime.setMinutes(minutes1);
targetTime.setHours(hours1);
if (value > 1430) {
targetTime.setMinutes(59);
targetTime.setHours(23)
}
var timeZoneFromDB = $(this).find('.comissionLabel').attr("data-offset");
$('#comission .time').each(function() {
var timeZoneFromDB = $(this).find('.comissionLabel').attr("data-offset");
var tzDifference = (parseInt(timeZoneFromDB) / 60) + targetTime.getTimezoneOffset();
var date = new Date(targetTime.getTime() + tzDifference * 60000);
var totallv = parseInt(date.getHours() * 60) + date.getMinutes();
$(this).find('.tooltip').css('margin-left', totallv / 3);
$(this).find('.tooltip').html(date.getHours() + ':' + date.getMinutes());
$(this).find('.comissionLabel').html(date.getHours() + ':' + date.getMinutes());
$(this).find('.custom-range').val(totallv)
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
<br><br><br> <br><br><br>
<div id="comission" class="col-md-6 col-md-offset-2">
<div class="col-md-12 mb-3 44 time">afghanistan
<span class="comissionLabel" data-offset='16200'>time: </span>
<input class="custom-range" value="60" type="range" min="0" max="1440" step="15">
</div>
<div class="col-md-12 mb-3 45 time"> Pakistan
<span class="comissionLabel" data-offset='18000'>time: </span>
<input class="custom-range" value="620" type="range" min="0" max="1440" step="15">
</div>
<div class="col-md-12 mb-3 46 time">indian
<span class="comissionLabel" data-offset='19800'>time: </span>
<input class="custom-range" value="620" type="range" min="0" max="1440" step="15">
</div>
</div>
</div>

Once the JS calculation is done, the next time it shows NAN value

I've done this JavaScript calculation. Live Preview
Everything is okay but the problem is, Once the calculation is done, the next time it shows NAN value. If you do not reload the page, then you can not calculation!
I want to repeat the calculation without reloading, how could it be?
Here Is my Simple Calculation:
// get all data
var first = document.getElementById('first');
var second = document.getElementById('second');
var third = document.getElementById('third');
var four = document.getElementById('four');
var five = document.getElementById('five');
var six = document.getElementById('six');
var seven = document.getElementById('seven');
var eight = document.getElementById('eight');
var outPut = document.getElementById('result');
// Listen for Submit the form
document.getElementById('gpaInput').addEventListener('submit', outPutF);
function outPutF(e){
e.preventDefault();
// Calculation
first = first.value * 5 / 100;
second = second.value * 5 / 100;
third = third.value * 5 / 100;
four = four.value * 15 / 100;
five = five.value * 15 / 100;
six = six.value * 20 / 100;
seven = seven.value * 25 / 100;
eight = eight.value * 10 / 100;
var result = first + second + third + four + five + six + seven + eight;
// Reset the form
this.reset();
// Finally output the Calculation
outPut.innerHTML = 'Your CGPA: '+result;
// setTimeout(window.location.reload(true), 9000);
}
input:focus, button:focus, select:focus {outline: none!important;box-shadow: none!important;}
#gpaInput .input-group {margin: 0.5em 0;}
#gpaInput .input-group-text { min-width: 95px;}
#result {display: block; width: 68%; text-align: center; margin-top: 25px; padding: 17px 0;}
.jumbotron {overflow: hidden;}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet"/>
<div class="container">
<div class="row justify-content-center">
<div class="col-lg-6">
<form id="gpaInput">
<div class="input-group">
<input id="first" type="number" step="any" class="form-control">
</div>
<div class="input-group">
<input id="second" type="number" step="any" class="form-control">
</div>
<div class="input-group">
<input id="third" type="number" step="any" class="form-control">
</div>
<div class="input-group">
<input id="four" type="number" step="any" class="form-control">
</div>
<div class="input-group">
<input id="five" type="number" step="any" class="form-control">
</div>
<div class="input-group">
<input id="six" type="number" step="any" class="form-control">
</div>
<div class="input-group">
<input id="seven" type="number" step="any" class="form-control">
</div>
<div class="input-group">
<input id="eight" type="number" step="any" class="form-control">
</div>
<hr>
<div class="mt-4">
<button type="submit" class="btn btn-info float-left p-3">Calculate CGPA</button>
<h5 id="result" class="alert alert-success float-right mt-0">Complete The form!</h5>
</div>
</form>
</div>
</div>
</div>
You get NaN because you are replacing the reference to the element with its value , so on the second time it is not longer the element.
var first = document.getElementById('first'); //<-- element
first = first.value * 5 / 100; //<-- first replaced with a number
so than next time you call it
first = first.value * 5 / 100; //<-- first.value is undefined here since first is a number
So you need to rename your variables inside...
var nFirst = first.value * 5 / 100;
var nSecond = second.value * 5 / 100;
var nThird = third.value * 5 / 100;
var nFour = four.value * 15 / 100;
var nFive = five.value * 15 / 100;
var nSix = six.value * 20 / 100;
var nSeven = seven.value * 25 / 100;
var nEight = eight.value * 10 / 100;
var result = nFirst + nSecond + nThird + nFour + nFive + nSix + nSeven + nEight;
You Should Declare your variables inside your function or you can get the value of every fields inside the function so that when the code runs for the next time it will get the values again correctly,
// Listen for Submit the form
document.getElementById('gpaInput').addEventListener('submit', outPutF);
function outPutF(e){
var first = document.getElementById('first');
var second = document.getElementById('second');
var third = document.getElementById('third');
var four = document.getElementById('four');
var five = document.getElementById('five');
var six = document.getElementById('six');
var seven = document.getElementById('seven');
var eight = document.getElementById('eight');
var outPut = document.getElementById('result');
e.preventDefault();
// Calculation
first = first.value * 5 / 100;
second = second.value * 5 / 100;
third = third.value * 5 / 100;
four = four.value * 15 / 100;
five = five.value * 15 / 100;
six = six.value * 20 / 100;
seven = seven.value * 25 / 100;
eight = eight.value * 10 / 100;
var result = first + second + third + four + five + six + seven + eight;
// Reset the form
this.reset();
// Finally output the Calculation
outPut.innerHTML = 'Your CGPA: '+result;
// setTimeout(window.location.reload(true), 9000);
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet"/>
<div class="container">
<div class="row justify-content-center">
<div class="col-lg-6">
<form id="gpaInput">
<div class="input-group">
<input id="first" type="number" step="any" class="form-control">
</div>
<div class="input-group">
<input id="second" type="number" step="any" class="form-control">
</div>
<div class="input-group">
<input id="third" type="number" step="any" class="form-control">
</div>
<div class="input-group">
<input id="four" type="number" step="any" class="form-control">
</div>
<div class="input-group">
<input id="five" type="number" step="any" class="form-control">
</div>
<div class="input-group">
<input id="six" type="number" step="any" class="form-control">
</div>
<div class="input-group">
<input id="seven" type="number" step="any" class="form-control">
</div>
<div class="input-group">
<input id="eight" type="number" step="any" class="form-control">
</div>
<hr>
<div class="mt-4">
<button type="submit" class="btn btn-info float-left p-3">Calculate CGPA</button>
<h5 id="result" class="alert alert-success float-right mt-0">Complete The form!</h5>
</div>
</form>
</div>
</div>
</div>

I have just formatted numbers to appear with commas but now my calculator doesn't work?

I am building a calculator, which I have previously asked questions on, see previous link: Building an interest rate calculator, however it won't produce figure
I want some fields to appear with commas when entered, I found some code on here and it seems to work with the formatting however now the calculations just return NaN.
Any ideas why adding commas would stop it from working?
Here's the code I used to add the commas and the code for the calculator is on the previous link:
HTML:
<div class="col-md-10 col-md-offset-1 form-body form-group">
<h2 class="form-heading">Find out how much your mortgage will cost</h2>
<div class="row text-muted">
<div class="col-md-5 col-md-offset-1 calc-input">
<h3>Purchase Price</h3>
<div class="input-group">
<span class="input-group-addon">£</span>
<input type="text" class="form-control comma" id="pp" placeholder="150,000" onchange="depositValue()">
</div>
<h3>Deposit</h3>
<div class="row text-muted">
<div class="col-md-4">
<div class="input-group">
<input type="text" class="form-control" id="percent" placeholder="10" onchange="depositValue()">
<span class="input-group-addon">%</span>
</div>
</div>
<div class="col-md-8">
<div class="input-group">
<span class="input-group-addon">£</span>
<input type="text" class="form-control comma" id="dp" placeholder="15,000" onchange="depositPercent()">
</div>
</div>
</div>
<h3>Mortgage Term</h3>
<div class="input-group">
<input type="text" class="form-control" id="mt" placeholder="25">
<span class="input-group-addon">Years</span>
</div>
<h3>Interest Rate</h3>
<div class="input-group">
<input type="text" class="form-control" id="ir" placeholder="4">
<span class="input-group-addon">%</span>
</div>
</div>
<div class="col-md-5 text-center">
<h3>Estimated Monthly Payment:</h3>
<p id="result"></p>
</div>
</div>
<div class="row text-muted">
<div class="col-md-10 col-md-offset-1 text-center">
<button class="btn btn-cta" onclick="calculate()">Calculate</button>
</div>
</div>
</div>
Calculator JS:
function calculate() {
var pp = document.getElementById("pp").value;
var dp = document.getElementById("dp").value;
var mt = document.getElementById("mt").value;
var ir = document.getElementById("ir").value;
var result = document.getElementById("result");
var la = parseInt(pp.replace(/,/g, ""), 10) - parseInt(dp.replace(/,/g, ""), 10);
var intRate = (ir/100)/12;
var months = mt * 12;
var monthlyPayment = ((((la*intRate)/(1-Math.pow(1+intRate,(-1*months)))*100)/100).toFixed(2));
result.innerHTML = "£" + monthlyPayment.replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
function depositValue() {
var pp = document.getElementById("pp").value;
var percent = document.getElementById("percent").value;
var dp = document.getElementById("dp");
var dpValue = (parseInt(percent.replace(/,/g, ""), 10) / 100) * parseInt(pp.replace(/,/g, ""), 10);
dp.value = dpValue;
}
function depositPercent() {
var pp = document.getElementById("pp").value;
var dp = document.getElementById("dp").value;
var percent = document.getElementById("percent");
var dpPercent = (parseInt(dp.replace(/,/g, ""), 10) / parseInt(pp.replace(/,/g, ""), 10) * 100).toFixed(0);
percent.value = dpPercent;
}
Comma JS (in another file):
$('input.comma').keyup(function(event) {
// skip for arrow keys
if(event.which >= 37 && event.which <= 40) return;
// format number
$(this).val(function(index, value) {
return value
.replace(/\D/g, "")
.replace(/\B(?=(\d{3})+(?!\d))/g, ",")
;
});
});
The moment you add the commas, it's no longer a number, but a string. When you do your calculations you'll have to account for that by stripping them out before processing.

Categories