function update() {
var object_one = $('#start_time');
var object_two = $('#total');
var object_three = $('#end-time');
var my_input = object_one.val();
var my_put = object_three.val();
var my_output = my_put - my_input;
object_two.val(my_output);
}
<th colspan="2"> Monday</th>
<td> <input id="start_time" type="time"></td>
<td> <input id= "end-time" type= "time"></td>
<td> <input id="start_time" type="time"></td>
<td> <input id= "end-time" type= "time"></td>
<td> in</td>
<td>out </td>
<td> in</td>
<td>out </td>
I've already defined the values of start and end time... i just don't how to subtract the times to get my output. I don't know if I'm setting the values correctly and that's why I get NaN as my output. It's a TIMESHEET assignment, so we have to add the time's in each row etc. I'm really new to this, help.
If you take a look at the value of your time inputs, they are strings. You can learn more about this type of time input here. The thing to note is that the value will always be a string in the format HH:MM (24 hour clock). This means it's easy to parse into hours/minutes.
I've made a function for you to do exactly this. You can find it here.
function ParseTime(timeString) {
var timeMatcher = /(\d\d):(\d\d)/;
var result = timeMatcher.exec(timeString);
// The first result (result 0) is the full string,
// the second is the number of hours, the third is the number of minutes.
var hours = Number(result[1]);
var minutes = Number(result[2]);
// returns the time in number of minutes.
return (hours * 60) + minutes;
}
Related
I have following function to calculate time between the start and the end (which are just input fields).
calculateTime() {
if(this.state.start !== '' && this.state.end !== ''){
let time1 = moment(this.state.end, "hh:mm");
let subtract = time1.subtract(this.state.start);
let format = moment(subtract).format("hh:mm");
console.log(format);
return format;
}
return 0;
}
In general the calculation works. The value gets set via a input field and the state gets updated to the entered value. As seen here:
<table>
<thead>
<tr>
<th>Date</th>
<th>Start</th>
<th>End</th>
<th>Time</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<input type="date" id="start" name="trip-start"
min="2022-01-01" max="2023-12-31" onChange={this.handleDate} value={this.state.date} />
</td>
<td>
<input type="text" onChange={this.handleStart} placeholder="hh:mm" maxLength={5} />
</td>
<td>
<input type="text" onChange={this.handleEnd} placeholder="hh:mm" maxLength={5} />
</td>
<td>
<p>{this.calculateTime()}</p>
</td>
</tr>
</tbody>
</table>
The function for setting the start state (setting the end value is similar except a other function gets called to update the state)
handleStart(event:any) {
this.setState({
start: event.target.value
});
}
As you can see in the pictures the values are off by 12h
Here it should be 13:01 instead of 01:01
Here it should be 00:01 instead of 12:01
Has anyone an idea how to fix that besides manually adding or removing the 12h?
Here is the working code :
const calculateTime = () => {
if (this.state.start !== "" && this.state.end !== "") {
let time1 = moment(this.state.end, "hh:mm");
let time2 = moment(this.state.start, "hh:mm");
let hoursDiff = time1.diff(time2, "hours");
console.log("Hours:" + hoursDiff);
let minutesDiff = time1.diff(time2, "minutes");
console.log("Minutes:" + minutesDiff);
// let subtract = time1.subtract(time2);
// let format = subtract.format("hh:mm");
// console.log(format);
return `${hoursDiff} : ${minutesDiff}`;
}
return 0;
};
Now, why your code didn't worked is beacuse, you need to wrap your startDate with moment,
let time2 = moment(this.state.start, "hh:mm");
let subtract = time1.subtract(time2);
when trying to do the both hour and mins. operation in single function it's adding locale time as well , I don't see any option to disable that. if you find something like that, you can use your code as well.
I hope this helps, after asking you to edit your question multiple times. :)
Also, looking at your use case, you should consider substracting the date with time , not just time
https://momentjscom.readthedocs.io/en/latest/moment/04-displaying/07-difference/
how can i get each input to equal zero before it is touched so that i dont get an error until every input is completed and not have it show in the input field. Also this is for money and im struggling to get the two decimal point thing down. thank you
<td>Subtotal</td>
<td class="total" id="tot" for="tot">
<input type="total" id="total">
<script type="text/javascript">
function myFunction()
{
var answer = document.getElementById('total');
var n = 0
var x = document.getElementById('itemprice');
var y = document.getElementById('itemprice1');
var z = document.getElementById('itemprice2');
//var d = document.getElementsById('itemprice3');
// parseFloat converts to values, otherwise you'll concatenate the strings.
answer.value = parseFloat(x[0].value) + parseFloat(y[0].value) + parseFloat(z[0].value); // + d.value;
}
</script>
</td>
give the item prices a zero default value:
<input type="total" id="itemprice" value="0.00">
There are 3 input fields.
Each has its own hidden input which helds value.
At this moment script works only for Bananas.(:-))
1 Banana is worth 1 banana OR 0.5 apple or 0.021 of a cookie(in other words 1 apple = 2 bananas, 46 bananas = cookie, 1 banana = 1 banana).
What I would like this script to do is to calculate values also for Apples and Cookies, and sum them up to show how much are they worth in "other" currencies.(for example show the price of 3 apples and 4 cookies in all 3 currencies)
I do realise that the code is very...well it would be a shame to call it code.
I just don't have any idea how to do it;
Any help would very appreciated.
Fiddle:
http://jsfiddle.net/eN7S6/9/
HTML:
<table>
<tr>
<td>
Apple<input name="inputone" id="inputone" class="calc" value="0"><span id="TotalOne"></span>
</td>
</tr>
<tr>
<td>
Banana<input name="inputtwo" id="inputtwo" class="calc" value="0"><span id="TotalTwo"></span>
</td>
</tr>
<tr>
<td>
Cookie<input name="inputthree" id="inputthree" class="calc" value="0"><span id="TotalThree"></span>
</td>
</tr>
</table>
<input name="multiplierone" id="multiplierone" class="calc" value="1" type="hidden" readonly>
<input name="multipliertwo" id="multipliertwo" class="calc" value="0.5" type="hidden" readonly>
<input name="multiplierthree" id="multiplierthree" class="calc" value="23" type="hidden" readonly>
<input type="button" id="update" value="Calculate" />
JQ:
$(document).ready(function() {
$('#update').click(function() {
var inputone = $('#inputone').val();
var multiplierone = $('#multiplierone').val();
var inputtwo = $('#inputtwo').val();
var multipliertwo = $('#multipliertwo').val();
var inputthree = $('#inputthree').val();
var multiplierthree = $('#multiplierthree').val();
var totalTotalOne = (inputtwo * multipliertwo);
var totalTotalTwo = (inputtwo);
var totalTotalThree = (inputtwo / multiplierthree / 2);
$('#TotalOne').text(totalTotalOne);
$('#TotalTwo').text(totalTotalTwo);
$('#TotalThree').text(totalTotalThree);
});
});
Well from what i gather from you description is that you want to get an amount that you have of a particular item. So if you have 10 bananas you want to calculate those 10 bananas against the other elements. The same goes for if you have 37 cookies you want to know how much its worth against the other items.
I believe that if you were to simplify your UI into two elements one being a input text field to enter amounts and another radio check collection, or it could be a selection field to select what type you have it will make better sense.
In your current setup you are not taking into account that your type(Apple, Banana, cookie) variable will change its only hard-coded to calculate bananas.
I quickly setup a jsbin to show you what i mean. Its just a start that may help you think of something else to do. Happy coding!
http://jsbin.com/EKisiGIK/10/edit
$(document).ready(function() {
$('#update').click(function() {
var inputone = parseFloat($('#inputone').val());
var multiplierone = parseFloat($('#multiplierone').val());
var inputtwo =parseFloat( $('#inputtwo').val());
var multipliertwo = parseFloat($('#multipliertwo').val());
var inputthree =parseFloat( $('#inputthree').val());
var multiplierthree = parseFloat($('#multiplierthree').val());
var totalTotalOne = (inputtwo * multipliertwo);
var totalTotalTwo = (inputtwo);
var totalTotalThree = (inputtwo / multiplierthree / 2);
$('#TotalOne').text(totalTotalOne);
$('#TotalTwo').text(totalTotalTwo);
$('#TotalThree').text(totalTotalThree);
});
});
Try this
One thing that you can do to make this problem simpler is to convert all currencies to a base currency before converting to their respective currencies. Using the example you have given i have converted all the currencies to their Cookie equivalent as it was the most valuable therefore removing the need to work with decimal values.
Change the HTML to
<input name="multiplierone" id="multiplierone" class="calc" value="23" type="hidden" readonly>
<input name="multipliertwo" id="multipliertwo" class="calc" value="46" type="hidden" readonly>
<input name="multiplierthree" id="multiplierthree" class="calc" value="1" type="hidden" readonly>
which is how many of each of the currencies it takes to make up one Cookie.
The following code can then be used to convert the currencies to Cookies
var base_total = inputone / multiplierone + inputtwo / multipliertwo + inputthree / multiplierthree;
var totalTotalOne = (base_total * multiplierone);
var totalTotalTwo = (base_total * multipliertwo);
var totalTotalThree = (base_total * multiplierthree);
this code will convert all the separate input values into their equivalent Cookie value. Once you have a total of all the fields as a cookie value it is a simple matter to convert that value back to all the respective currency values.
Fiddle
I am making a loan payment calculator on my website (www.kreditrunner.dk - In the bottom of the page).
EDIT: Problem solved with the following equation:
var princ = document.getElementById("amount").value;
var intr = document.getElementById("earlypercent").value/1200;
var term = document.getElementById("time").value;
document.getElementById("result").value = princ * intr / (1 - (Math.pow(1/(1 + intr), term)));
And also i used a keyup function instead. Cause when the key is pressed down, the input hasn't received the value yet, hence the wrong result :)
ORIGINAL POST:
I have my four inputs with respectively amount, interest rate per year in percent, payment period, and result.
<table>
<tr>
<td width="150">
<label for="amount">Lånebeløb (DKK)</label>
<input type="text" id="amount" name="amount" class="input-small">
<label for="earlypercent">ÅOP (%)</label>
<input type="text" id="earlypercent" name="earlypercent" class="input-small">
</td>
<td>
<label for="time">Løbetid (Mdr)</label>
<input type="text" id="time" name="time" class="input-small">
<label for="result"><b>Månedlig betaling (DKK)</b></label>
<input type="text" id="result" name="result" class="input-medium">
</td>
</tr>
</table>
For each of the first three input I have the listed calculations seen below which is derived from the following equation: http://www.wikihow.com/Calculate-a-Loan-Payment
$('#amount').keydown(function () {
var amount = document.getElementById("amount").value;
var earlypercent = document.getElementById("earlypercent").value;
var monthlypercent = earlypercent / 12 * 100;
var time = document.getElementById("time").value;
var negativetime = time * (-1);
var result = 1 + monthlypercent;
result = Math.pow(result, negativetime);
result = 1 - result;
result = monthlypercent / result;
document.getElementById("result").value = result * amount;
});
However, my result is weird as ****. As you can see when you try (e.g. with values, 1000, 10%, 12 months) the result is 8333.33 where it should have been around 83.33. Well actually it should be around 87.95.
So i could move the *100 in the montlypercent, however as you see when write an amount and tab to the next input field, the result changes even though the values are the same. Cant seem to get the equation right and the keydown function bothers me :/
Please help :)
I have a table and want to calculate each element like:
calc-this-cost * calc-this-cost(value of checkbox) = calc-this-total
Then summ all calc-this-cost and put it to totalcost div.
This is table:
<td class="params2">
<table id="calc-params">
<tr>
<td>aaa</td><td class="calc-this-cost">159964</td><td class="calc-this-count">
<input type="checkbox" name="a002" value="0" onclick="calculate(this);" />
</td><td class="calc-this-total">0</td>
</tr>
<tr>
<td>bbb</td><td class="calc-this-cost">230073</td><td class="calc-this-count">
<input type="checkbox" name="a003" value="0" onclick="calculate(this);" />
</td><td class="calc-this-total">0</td>
</tr>
<tr>
<td>ccc</td><td class="calc-this-cost">159964</td><td class="calc-this-count">
<input type="checkbox" name="a004" value="1" onclick="calculate(this);" />
</td><td class="calc-this-total">0</td>
</tr>
........
</table>
.......
</td>
<div id="calc-total-price">TOTAL COST: <span>0</span></div>
My script (in function calculate)
var totalcost=0;
$('.params2 tr').each(function(){
var count=parseFloat($('input[type=checkbox]',$(this)).attr('value'));
var price=parseFloat($('.calc-this-cost',$(this)).text().replace(" ",""));
$('.calc-this-total',$(this)).html(count*price);
totalcost+=parseFloat($('.calc-this-cost',$(this)).text());
});
$('#calc-total-price span').html(totalcost);
Counting each element and put result to calc-this-cost - work perfect.
But totalcost result NaN. Why?
[general] don't parseFloat() more than you need to
[general] move repeating code to functions
[jQuery] use .find() over context and cache nodes ($row)
[general] look at how String.replace() works
[general] look at Number.toFixed() for displaying floats
example
var totalcost = 0,
toFloat = function(value) {
// remove all whitespace
// note that replace(" ", '') only replaces the first _space_ found!
value = (value + "").replace(/\s+/g, '');
value = parseFloat(value || "0", 10);
return !isNaN(value) ? value : 0;
};
$('.params2 tr').each( function() {
var $row = $(this),
count = toFloat($row.find('.calc-this-count input').val()),
price = toFloat($row.find('.calc-this-cost').text()),
total = count * price;
$row.find('calc-this-total').text(total.toFixed(2));
totalcost += total;
});
$('#calc-total-price span').text(totalcost.toFixed(2));
console.log() will solve all your problems:
$('.params2 tr').each(function(){
var count=parseFloat($('input[type=checkbox]',$(this)).attr('value'));
var price=parseFloat($('.calc-this-cost',$(this)).text().replace(" ",""));
$('.calc-this-total',$(this)).html(count*price);
totalcost+=parseFloat($('.calc-this-cost',$(this)).text());
console.log(count, price, totalcost)
});
Add more logging where every you don't understand something. Didn't I just tell you to use logging? :)