javascript simple loop calculation - javascript

function calc() {
var aa = document.getElementById("aa").value;
var bb = document.getElementById("bb").value;
var cc = document.getElementById("cc").value;
var time = 1;
var dd = document.getElementById("dd").value / 365;
first = 1 + ((bb / 100) / cc);
second = cc * time;
result = aa * Math.pow(first, second);
bb_earn = aa * Math.pow(first, second) - aa;
final = Number(aa) + Number(bb_earn);
var r = "";
var lastTotal = aa;
for (var i = 0; i < dd; i++) {
var newTotal = Number(lastTotal) + Number(bb_earn);
zz = +newTotal;
lastTotal = newTotal;
r += i + 1 + ") " + aa + "---" + zz + "---" + final + "<br/>";
r += "";
}
document.getElementById("table").innerHTML += r;
}
<div> A - <input type="text" id="aa" value="12000" /></div>
<div> B - <input type="text" id="bb" value="20" /></div>
<div> C - <input type="text" id="cc" value="1" /></div>
<div> D - <input type="text" id="dd" value="1825" /></div>
<div> <input type="button" value="Get" onclick="calc();" /></div>
<br/><br/>
<div id="table"></div>
I am trying to loop the default value, 20% of default value and sum of default value plus 20% of default value. In next row, default value should be previous final column sum value. I tried above javascript calculation to achieve the desired result. But, I messed up..
Output result is:
1) 12000---14400---14400
2) 12000---16800---14400
3) 12000---19200---14400
4) 12000---21600---14400
5) 12000---24000---14400
But, Output should be:
1) 12000---2400---14400
2) 14400---2880---17280
3) 17280---3456---20736
4) 20736---4147.20---24883.20
5) 24883.20---4976.60---29859.80

It's a bit hard to figure out what you're trying to achieve with the code, based on what you write. It could be written a lot more simple if you merely wanted to take the previous total and add 20% each time. You don't explain what time variable does and what the #cc element does.
Regardless of that, this should output the result you expect.
function calc() {
var aa = document.getElementById("aa").value;
var bb = document.getElementById("bb").value;
var cc = document.getElementById("cc").value;
var dd = document.getElementById("dd").value / 365;
var r = "";
var lastTotal = Number(aa);
for (var i = 0; i < dd; i++) {
var ratio = ((bb / 100) / cc);
var addition = lastTotal * ratio;
var newTotal = lastTotal + addition;
r += i + 1 + ") " + lastTotal + "---" + addition + "---" + newTotal + "<br/>";
r += "";
lastTotal = newTotal;
}
document.getElementById("table").innerHTML += r;
}
<div> A - <input type="text" id="aa" value="12000" /></div>
<div> B - <input type="text" id="bb" value="20" /></div>
<div> C - <input type="text" id="cc" value="1" /></div>
<div> D - <input type="text" id="dd" value="1825" /></div>
<div> <input type="button" value="Get" onclick="calc();" /></div>
<br/><br/>
<div id="table"></div>

There is nothing wrong with the for next loop
But i guess everything is wrong with your formulas.
<!DOCTYPE HTML>
<html>
<head>
<title>Untitled</title>
</head>
<body>
<div> A - <input type="text" id="aa" value="12000" /></div>
<div> B - <input type="text" id="bb" value="20" /></div>
<div> C - <input type="text" id="cc" value="1" /></div>
<div> D - <input type="text" id="dd" value="1825" /></div>
<div> <input type="button" value="Get" onclick="calc();" /></div>
<br/><br/>
<div id="table"></div>
<script>
function calc(){
var aa = document.getElementById("aa").value*1.0;//ensure that we use numbers and not strings
var bb = document.getElementById("bb").value*1.0;
var cc = document.getElementById("cc").value*1.0;
var time = 1.0;
var dd = document.getElementById("dd").value*1 / 365;
first = 1 + ((bb / 100) / cc);//first = 1.2 bb 20 ,cc 1
second = cc * time; // 1*1=1
// i guess here you make a mistake or choose the wrong test datas
var fact=Math.pow(first, second) // fact = 1.2^1
result = aa * fact; //result 14400 = 12000*1.2;
bb_earn = aa * fact - aa; // bb_earn = 1.2 * 12000 -12000 = .2*12000 =2400
final = aa + bb_earn; //final =12000 + 2400 = again 14400
var zz=0;
var r = "";
var lastTotal = aa;
for (var i = 0; i < dd; i++) {
// as you could see thére is by this numbers NO chance to get something like -4147.20
// there are NO AFTER DIGITS in this calculation
//based on the fact result not possible
var newTotal = Number(lastTotal) + Number(bb_earn);
zz = newTotal;
lastTotal = newTotal;
r += i + 1 + ") " + aa + "---" + zz + "---" + final + "<br/>";
r += "";
}
document.getElementById("table").innerHTML += r;
}
</script>
</body>
</html>

Related

Create a function to compare 2 numbers

I'm writing a function to calculate the sum, product, and see which number is greater. I have the sum and product, but when I try to compare the 2 numbers, it won't work. I'm trying to get all 3 items (sum, product, and comparison) to show when the button is clicked. Here is the code:
<div class="container">
<div class="main">
<h1>Please enter two numbers</h1>
<p>First number: <input type="number" id="num1"> Second number: <input type="number" id="num2"></p>
<input type="button" id="btn" value="Submit" onclick="calculate()">
</div>
<br>
<div id="result">
</div>
<!-- Function -->
<script>
function calculate() {
var x = document.getElementById("num1").value;
var y = document.getElementById("num2").value;
var sum = parseInt(x) + parseInt(y);
var product = parseInt(x) * parseInt(y);
document.querySelector("#result").innerHTML = ("The sum is " +
sum + " and the product is " + product);
}
</script>
<!-- This was the if statement that won't work. I was placing this in the same function right after the 1st querySelector.
if (x > y) {
document.querySelector("#result").innerHTML = (x + " is greater than " + y);
} else {
document.querySelector("#result").innerHTML = (y + " is greater than " + x);
}
-->
I moved the cast of x and y into integers to the assignment of that variables. Afterwards you can just use them as integers without worrying.
function calculate() {
var x = parseInt(document.getElementById("num1").value);
var y = parseInt(document.getElementById("num2").value);
var sum = x + y;
var product = x * y;
document.querySelector("#result").innerHTML = ("The sum is " +
sum + " and the product is " + product + ". ");
if (x > y) {
document.querySelector("#result").innerHTML += (x + " is greater than " + y);
// TODO: what about x == y ?
} else {
document.querySelector("#result").innerHTML += (y + " is greater than " + x);
}
}
<div class="container">
<div class="main">
<h1>Please enter two numbers</h1>
<p>First number: <input type="number" id="num1"> Second number: <input type="number" id="num2"></p>
<input type="button" id="btn" value="Submit" onclick="calculate()">
</div>
<br>
<div id="result">
</div>
Don't parse the numbers several times. Parse them once and then use the parsed values.
Similarly, don't use querySelector to get the same element several times, use it once and save it into a variable that you can use later.
And since you're getting the element by ID, then it is better to use getElelementByID() instead of querySelector().
function calculate() {
var x = document.getElementById("num1").value;
var y = document.getElementById("num2").value;
x = parseInt(x);
y = parseInt(y);
var sum = x + y;
var product = x * y;
var result = document.querySelector("#result");
result.innerHTML = "The sum is " + sum + " and the product is " + product + "<br/>";
if (x > y) {
result.innerHTML += x + " is greater than " + y;
} else {
result.innerHTML += y + " is greater than " + x;
}
}
<div class="container">
<div class="main">
<h1>Please enter two numbers</h1>
<p>First number: <input type="number" id="num1"> Second number: <input type="number" id="num2"></p>
<input type="button" id="btn" value="Submit" onclick="calculate()">
</div>
<br>
<div id="result">
</div>
Basically your Problem is that in your code you are overwriting your div element twice.for ex Your div element result for:
```
if (x > y) {
document.querySelector("#result").innerHTML = (x + " is greater than " + y);
} else {
document.querySelector("#result").innerHTML = (y + " is greater than " + x);
}
```
is replaced by immediate following value:
```
document.querySelector("#result").innerHTML = ("The sum is " +sum + " and the product is " + product);
```
I suggest you to either concatenate both innerHTML values or make a seperate div element for either of them.
Hope this will help you.

js - how to output values from function into HTML table

I've created a calculator to show repayments over the term of the loan.
I've managed to calculate each months payment, interest, remaining loan but I'm trying to output this into a table. The columns will be a fixed number (5) but the rows should dynamically update based on the number of months.
I've seen a few similar posts but can't get it to work for my code.
Code below and in jsfiddle
HTML
<div class="mortgageInput">
<form method="POST" name="calc" onclick="validateForm();repayment();return false;">
<label>Amount </label>
<input type="textbox" id="loan" value="100000"><br>
<label>Years</label>
<input type="textbox" id="years" value="15"><br>
<label>Rate (%)</label>
<input type="textbox" id="rate" value="6.00" onkeyup="calculate"><br>
<input type="button" value="Calculate" id="btn"><br>
<label>Monthly Repayment</label>
<input type="textbox" id="monthlyRepayment"><br>
<label>Monthly Interest Only</label>
<input type="textbox" id="interest"><br>
<label>Monthly Capital Repayment</label>
<input type="textbox" id="capitalRepayment"><br>
<label>Total Interest</label>
<input type="textbox" id="totalInterest">
</form>
</div>
<br>
Output into table...<p id="demo"></p>
JS
(document).on("keyup", calculate());
function validateForm(){
var validation = true;
validation &= calculate();
validation &= pmt();
return validation;
}
function calculate() {
var p = document.querySelector("#loan").value;
var y = document.querySelector("#years").value;
var rate = document.querySelector("#rate").value;
var r = rate / 100 / 12;
var n = y * 12;
var I = (p * r);
var monthlyPayment = -pmt(r,n,p);
var mr = (monthlyPayment - I);
var ti = (monthlyPayment) * n - p;
var list = JSON.stringify((computeSchedule(p, rate, 12, y, monthlyPayment)), 0, 4);
document.querySelector("#interest").value = I.toFixed(2);
document.querySelector("#totalInterest").value = ti.toFixed(2);
document.querySelector("#capitalRepayment").value = mr.toFixed(2);
document.querySelector("#monthlyRepayment").value = monthlyPayment.toFixed(2);
document.getElementById("demo").innerHTML = list;
}
function pmt(rate,nper,pv) {
var pvif, pmt;
pvif = Math.pow( 1 + rate, nper);
pmt = rate / (pvif - 1) * -(pv * pvif);
return pmt;
}
function computeSchedule(loan_amount, interest_rate, payments_per_year, years, payment) {
var schedule = [];
var remaining = loan_amount;
var number_of_payments = payments_per_year * years;
for (var i=0; i<=number_of_payments; i++) {
var interest = remaining * (interest_rate/100/payments_per_year);
var principle = (payment-interest);
var row = [i, payment, interest>0?interest:0, principle>0?principle:0, remaining>0?remaining:0];
schedule.push(row);
remaining -= principle
}
return schedule;
}
the above answer is right but if concern about performance do insert html outside loop
var list = computeSchedule(p, rate, 12, y, monthlyPayment);
var tables = "";
for (var i = 0; i < list.length; i++) {
tables += "<tr>" +
"<td>" + list[i][0] + "</td>" +
"<td>" + list[i][1] + "</td>" +
"<td>" + list[i][2] + "</td>" +
"<td>" + list[i][3] + "</td>" +
"<td>" + list[i][4] + "</td>" +
"</tr>";
}
document.getElementById("demo").innerHTML = '<table>' + tables + '</table>';
I am not sure if I understand you correctly, but this should normally be the solution. You're fiddle printed some js errors, I haven't fixed them in this example.
function validateForm(){
var validation = true;
validation &= calculate();
validation &= pmt();
return validation;
}
function calculate() {
var p = document.querySelector("#loan").value;
var y = document.querySelector("#years").value;
var rate = document.querySelector("#rate").value;
var r = rate / 100 / 12;
var n = y * 12;
var I = (p * r);
var monthlyPayment = -pmt(r,n,p);
var mr = (monthlyPayment - I);
var ti = (monthlyPayment) * n - p;
var list = JSON.stringify((computeSchedule(p, rate, 12, y, monthlyPayment)), 0, 4);
document.querySelector("#interest").value = I.toFixed(2);
document.querySelector("#totalInterest").value = ti.toFixed(2);
document.querySelector("#capitalRepayment").value = mr.toFixed(2);
document.querySelector("#monthlyRepayment").value = monthlyPayment.toFixed(2);
var list = computeSchedule(p, rate, 12, y, monthlyPayment);
console.log(list.length);
for (var i=0; i < list.length; i++) {
document.getElementById("test").innerHTML += "<tr><td>" + list[i][0] + "</td><td>" + list[i][1] + "</td><td>" + list[i][2] + "</td><td>" + list[i][3] + "</td><td>" + list[i][4] + "</td></tr>";
}
}
function pmt(rate,nper,pv) {
var pvif, pmt;
pvif = Math.pow( 1 + rate, nper);
pmt = rate / (pvif - 1) * -(pv * pvif);
return pmt;
}
function computeSchedule(loan_amount, interest_rate, payments_per_year, years, payment) {
var schedule = [];
var remaining = loan_amount;
var number_of_payments = payments_per_year * years;
for (var i=0; i<=number_of_payments; i++) {
var interest = remaining * (interest_rate/100/payments_per_year);
var principle = (payment-interest);
var row = [i, payment, interest>0?interest:0, principle>0?principle:0, remaining>0?remaining:0];
schedule.push(row);
remaining -= principle
}
return schedule;
}
table {
border-spacing: 0;
}
table td {
border: 1px solid #666;
padding: 0 3px;
}
<div class="mortgageInput">
<form method="POST" name="calc" onclick="validateForm();repayment();return false;">
<label>Amount </label>
<input type="textbox" id="loan" value="100000"><br>
<label>Years</label>
<input type="textbox" id="years" value="15"><br>
<label>Rate (%)</label>
<input type="textbox" id="rate" value="6.00" onkeyup="calculate"><br>
<input type="button" value="Calculate" id="btn"><br>
<label>Monthly Repayment</label>
<input type="textbox" id="monthlyRepayment"><br>
<label>Monthly Interest Only</label>
<input type="textbox" id="interest"><br>
<label>Monthly Capital Repayment</label>
<input type="textbox" id="capitalRepayment"><br>
<label>Total Interest</label>
<input type="textbox" id="totalInterest">
</form>
</div>
<br>
<table id="test">
</table>
The result of computeSchedule contains a two dimensional array. You should be able to loop through it with two nested for loops. Then you can compose your table.
Very simple example would look like this:
var demoList = computeSchedule(p, rate, 12, y, monthlyPayment);
var table = "<table>";
for (var rowIndex=0; rowIndex <= n; rowIndex++) {
var row = "<tr><td>#" + rowIndex + "</td>";
for(var colIndex = 0; colIndex < 4; colIndex++) {
row += "<td>" + demoList[rowIndex][colIndex] + "</td>";
}
table += row + "</tr>";
}
document.getElementById("output").innerHTML = table + "</table>";
You can also try the life version here: https://fiddle.jshell.net/aua4g8e7/

In the output shown in undefined + string how can i remove this

function reverse_string() {
var text = document.getElementById("string_reverse").value;
var split_string = text.split(" ");
var output = "";
var output2 = "";
function isEven(split_string) {
if (split_string.length % 2 == 0)
return output;
else
return output2;
}
for (var i = 0; i < split_string.length; i += 2) {
output += " " + split_string[i + 1] + " " + split_string[i];
document.getElementById("reverse").innerHTML = output;
}
output2 += " " + output + " " + split_string[split_string.length - 1];
document.getElementById("reverse").innerHTML = output2;
}
<div class="row">
<div class="col-sm-3">Input Any string :
<input type="text" style="width:250px" name="STRAT_TIME" id="string_reverse" placeholder="ex: w1 w2 w3 w4 w5 w6 w7 w8">
</div>
<div class="col-sm-3">
<INPUT NAME="check" TYPE=Button VALUE="string reverse" onClick="reverse_string(); return false;">
</div>
</div>
<div id="reverse" class="row">
</div>
Output shown: undefined + string.
How can i remove this?
I like it if input is 1 2 3 4 then o/t is 2 1 4 3
and another condition is if string is odd
ex 1 2 3 4 5 then needed 2 1 4 3 5
Try this
for (var i = split_string.length-1; i >= 0; i --) {
output += " " + split_string[i ] + " ";
}
document.getElementById("reverse").innerHTML = output;
function reverse_string() {
var text = document.getElementById("string_reverse").value;
var split_string = text.split(" ");
var output = "";
var output2 = "";
function isEven(split_string) {
if (split_string.length % 2 == 0)
return output;
else
return output2;
}
for (var i = split_string.length-1; i >= 0; i --) {
output += " " + split_string[i ] + " ";
}
document.getElementById("reverse").innerHTML = output;
}
<div class="row">
<div class="col-sm-3">Input Any string :
<input type="text" style="width:250px" name="STRAT_TIME" id="string_reverse" placeholder="ex: w1 w2 w3 w4 w5 w6 w7 w8">
</div>
<div class="col-sm-3">
<INPUT NAME="check" TYPE=Button VALUE="string reverse" onClick="reverse_string(); return false;">
</div>
</div>
<div id="reverse" class="row">
</div>
That is because, you are splitting using " " and using split_string[i + 1].
If I enter "Hello World! Foo."
split_string will be like
0: Hello
1: World!
2: Foo.
First Iteration will work fine. Then you increment as i+=2, so now i is 2 and split_string[i + 1] will be split_string[3] i.e. undefined.
Same will happen if you do not enter value with any spaces.
You can try something like this:
function reverse_string() {
var text = document.getElementById("string_reverse").value;
var split_string = text.split(" ");
var _temp = [];
var len = split_string.length;
console.log(len, split_string)
for(var i=0; i<len/2; i++){
_temp.push(split_string[(i*2) + 1]);
_temp.push(split_string[(i*2)]);
}
console.log(_temp);
document.getElementById("reverse").innerHTML = _temp.join(" ");
}
<div class="row">
<div class="col-sm-3">Input Any string :
<input type="text" style="width:250px" name="STRAT_TIME" id="string_reverse" placeholder="ex: w1 w2 w3 w4 w5 w6 w7 w8">
</div>
<div class="col-sm-3">
<INPUT NAME="check" TYPE=Button VALUE="string reverse" onClick="reverse_string(); return false;">
</div>
</div>
<div id="reverse" class="row">
</div>
Try this simple method...
var str = "1234567";
var newstr = "";
for (var i = 0; i < str.length; i++) {
if (i == 0 || i % 2 === 0) {
var j =i+1;
if(typeof str[j] === "undefined"){
newstr = newstr + str[i];
}else{
newstr = newstr + str[i + 1] + str[i];
}
}
}
Hope this help you...
DEMO

How to add two input time values and display it in another input box?

I am getting two durations, current time and previous time from user. now, i want to calculate the total time show it on the third textbox.
<p><span>Current Duration</span><input id="txt1" onblur="sum();" type="text" autocomplete="off" name="current_duration" value="" /></p>
<p><span>Previous Duration</span><input id="txt2" onblur="sum();" type="text" autocomplete="off" name="previous_duration" value="" /></p>
<p><span>Total Duration</span><input id="txt3" type="text" readonly autocomplete="off" name="total_duration" value="" /></p>
<script>
function sum() {
var txtFirstNumberValue = document.getElementById('txt1').value;
var txtSecondNumberValue = document.getElementById('txt2').value;
var result = parseInt(txtFirstNumberValue) + parseInt(txtSecondNumberValue);
if (!isNaN(result)) {
document.getElementById('txt3').value = result;
}
}
</script>
How can i implement the same? can you guys help me out?
Assumning the separator between time and minutes is '.', this will work. If another separator i needed, just replace the character in toTime() and fromTime()
<p><span>Current Duration</span><input id="txt1" onblur="sum();" type="text" autocomplete="off" name="current_duration" value="" /></p>
<p><span>Previous Duration</span><input id="txt2" onblur="sum();" type="text" autocomplete="off" name="previous_duration" value="" /></p>
<p><span>Total Duration</span><input id="txt3" type="text" readonly autocomplete="off" name="total_duration" value="" /></p>
<script>
function sum() {
var txtFirstNumberValue = document.getElementById('txt1').value;
var txtSecondNumberValue = document.getElementById('txt2').value;
var result = fromTime(txtFirstNumberValue) + fromTime(txtSecondNumberValue);
if (!isNaN(result)) {
document.getElementById('txt3').value = toTime(result);
}
}
function fromTime(time) {
var timeArray = time.split('.');
var hours = parseInt(timeArray[0]);
var minutes = parseInt(timeArray[1]);
return (hours * 60) + minutes;
}
function toTime(number) {
var hours = Math.floor(number / 60);
var minutes = number % 60;
return hours + "." + (minutes <= 9 ? "0" : "") + minutes;
}
</script>
JsFiddle
I have find this from SO.
You can try this:
function sum()
{
var datetime = document.getElementById('txt1').value;
var txtSecondNumberValue = document.getElementById('txt2').value;
var datetime = new Date(datetime).getTime();
var now = new Date(txtSecondNumberValue).getTime();
if( isNaN(datetime) )
{
return "";
}
console.log( datetime + " " + now);
if (datetime < now) {
var milisec_diff = now - datetime;
}else{
var milisec_diff = datetime - now;
}
var days = Math.floor(milisec_diff / 1000 / 60 / (60 * 24));
var date_diff = new Date( milisec_diff );
return days + "d "+ (date_diff.getHours() - 5) + "h " + (date_diff.getMinutes() - 30) + "m";
}

dividing two variables in javascript

ok, so I am trying to make a midpoint calculator in JavaScript for fun and to practice with the language, The formula is pretty simple, it is just x1 + x2 / 2 and y1 + y2 / 2, I want the user to be able to define the x and y coordinates, and this is what I have come up with:
alert("welcome to nate's midpoint calculator!");
var x1 = prompt("type your first x coordanate!");
var y1 = prompt("excelent!, now your first y coordanate!");
var x2 = prompt("now type your second x coordanate!");
var y2 = prompt("and finally, your last y coordanate!");
var midText = ("your midpoints are: ");
var comma = (",");
var exclam = ("!");
var two = (2)
var x1x2 = (x1 + x2 / two);
var y1y2 = (y2 + y2 / two );
alert(midText + x1x2 + comma + y1y2 + exclam);
for some reason, this is not calculating correctly and turning in wrong answers, go ahead and try it out. it may be some weird misstype from me, I am fairly new to javascript, only having worked with the language for an hour or two. any help would be very much appreciated! thanks in advance!
(x1 + x2 / two)
is dividing then concatenating a string and a number.
Try
((+x1 + +x2) / two)
which uses the prefix + operator to coerce strings to numbers and parenthesizes the low-precedence addition.
You can see this in action by doing
alert(("1" + "0") / 2) // alerts 5 since "1" + "0" == "10"
alert((1 + 0) / 2) // alerts 0.5 since 1 + 0 == 1
perhaps you need
var x1x2 = (parseInt(x1) + parseInt(x2)) / two;
var y1y2 = (parseInt(y2) + parseInt(y2)) / two;
Demo jsFiddle
JS
alert("welcome to nate's midpoint calculator!");
var x1 = prompt("type your first x coordanate!");
var y1 = prompt("excellent!, now your first y coordanate!");
var x2 = prompt("now type your second x coordanate!");
var y2 = prompt("and finally, your last y coordanate!");
var midText = ("your midpoints are: ");
var x1x2 = (+x1 + +x2) / 2;
var y1y2 = (+y2 + +y2) / 2 ;
alert(midText + x1x2 + "," + y1y2 + "!");
The way I would do it (jsFiddle)
HTML
<h1>Welcome to Nate's midpoint calculator!</h1>
<form>
<div>
<label for="x1">X1</label>
<input type="textbox" id="x1" />
<label for="y1">Y1</label>
<input type="textbox" id="y1" />
</div>
<div>
<label for="x2">X2</label>
<input type="textbox" id="x2" />
<label for="y2">Y2</label>
<input type="textbox" id="y2" />
</div>
<div>
<input type="submit" value="Calculate" onclick="Calculate()"/>
</div>
</form>
<div>
<span id="results"></span>
</div>
JS
function Calculate(){
event.preventDefault();
var x1 = parseFloat(document.getElementById('x1').value);
var y1 = parseFloat(document.getElementById('y1').value);
var x2 = parseFloat(document.getElementById('x2').value);
var y2 = parseFloat(document.getElementById('y2').value);
var x1x2 = parseFloat((x1 + +x2) / 2);
var y1y2 = parseFloat((+y2 + +y2) / 2);
document.getElementById("results").innerHTML=("your midpoints are: " + x1x2 + "," + y1y2 + "!");
}
Using KnockoutJS
HTML
<h1>Welcome to Nate's midpoint calculator!</h1>
<div>
<label for="x1">X1</label>
<input type="textbox" id="x1" data-bind="value: x1" />
<label for="y1">Y1</label>
<input type="textbox" id="y1" data-bind="value: y1" />
</div>
<div>
<label for="x2">X2</label>
<input type="textbox" id="x2" data-bind="value: x2" />
<label for="y2">Y2</label>
<input type="textbox" id="y2" data-bind="value: y2" />
</div>
<div>
your midpoints are: <span id="results" data-bind="text: Midpoint"></span>!
</div>
JS
var MidpointCalulatorViewModel = function () {
var self = this;
self.x1 = ko.observable();
self.x2 = ko.observable();
self.y1 = ko.observable();
self.y2 = ko.observable();
self.x1x2 = ko.computed(function () {
return parseFloat((parseFloat(self.x1()) + parseFloat(self.x2())) / 2);
}, self);
self.y1y2 = ko.computed(function () {
return parseFloat((parseFloat(self.y1()) + parseFloat(self.y2())) / 2);
}, self);
self.Midpoint = ko.computed(function () {
return self.x1x2() + "," + self.y1y2();
}, self);
};
ko.applyBindings(new MidpointCalulatorViewModel());
Note you need validation

Categories