This is the Html form I use.
<form name="calculate" method="get" action="#" onsubmit="return Validate()">
<label>Enter a number</label>
<input id="numb1" name="numb1" id="numb2" placeholder="Number 1">
<label>Enter another number</label>
<input id="numb2" name="numb2" id="numb2" placeholder="Number 2">
<label>Result</label>
<textarea style="text-align:center; height:85px; max-height:85px;" name="summ" id="summ" disabled="disabled" placeholder="Result" dir="ltr"></textarea>
<br />
<input id="calc" name="calc" type="submit" value="Calculate!">
The JS
function Validate() {
if (calculate.numb1.value == "" || calculate.numb2.value == "") {
alert("Check the form again");
calculate.numb1.focus();
document.getElementById('summ').value = "";
return (false);
}
Update()
return (true);
}
function Update() {
var plus = calculate.numb1.value + calculate.numb2.value;
var minus = calculate.numb1.value - calculate.numb2.value;
var mult = calculate.numb1.value * calculate.numb2.value;
var div = calculate.numb1.value / calculate.numb2.value;
var multi = document.getElementById("summ").value = calculate.numb1.value + "+" + calculate.numb2.value + "=" + plus + "\n" + calculate.numb1.value + "-" + calculate.numb2.value + "=" + minus + "\n" + calculate.numb1.value + "*" + calculate.numb2.value + "=" + mult + "\n" + calculate.numb1.value + "/" + calculate.numb2.value + "=" + div;
}
All the calculations work perfectly accept the Plus function.
When you type 4+4 for example you get 44...
I tried parseFloat, but still, nothing changes.
var numb1 = parseFloat(document.calculate.numb1.value);
var numb2 = parseFloat(document.calculate.numb2.value);
var plus = numb1 + numb2;
var minus = numb1 - numb2;
var mult = numb1 * numb2;
var div = numb1 / numb2;
Convert them to numbers first.
Do this with every calculation with a string value.
var plus = Number(calculate.numb1.value) + Number(calculate.numb2.value);
Léon
Related
This simple code is supposed to give an alert when the button is pressed the amount of times you wrote in the input. There is no error or something but the code just doesn't work. Am I stupid and did I miss something or is the logic of my code just wrong? and how do make it work?
var rand1, rand2, text1, text2
let count = 0;
var correct = 0;
function button(){
text1 = document.getElementById("number").value;
rand1 = Math.floor(Math.random() * text1);
rand2 = Math.floor(Math.random() * text1);
var html = "<br><br><input type='number' id='id'> <button onclick=' check() '> check </button> " + Number(rand2) + '+' + Number(rand1);
document.getElementById('div').innerHTML = html;
}
function check(){
text2 = document.getElementById('questions').value;
var answer = rand1 + rand2;
var text11 = document.getElementById('id').value;
if(answer == text11) {
var h = "<input type='number' id='id'> " + " <button onclick=' check() '> check </button> " + correct + '/' + text2 + '<br>' + count;
document.getElementById('div').innerHTML = h;
setTimeout(wait, 3000);
document.getElementById("but").disabled = true;
correct = correct + 1;
count = count + 1;
} else {
count = count + 1;
var b = "<input type='number' id='id'> " + " <button onclick=' check() '> check </button> " + correct + '/' + text2 + '<br>' + count;
document.getElementById('div').innerHTML = b;
setTimeout(wait, 3000);
document.getElementById("but").disabled = true;
}
if (count === text2){
alert(correct + '/' + text2);
}
function wait(){
button()
}
}
<p>maximum number:<input type="text" id="number"></p>
<p>how many questions?<input type="text" id="questions"></p>
<button onclick="button()" id = 'but'> ok </button>
<div id = 'div'> </div>
The .value returns a string and you must convert it into a number (if you want to) before using it.
So in line 6 do this:
text1 = Number(document.getElementById("number").value);
and also in the check() function:
text2 = Number(document.getElementById('questions').value);
Hope that works.
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>
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.
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/
I want to display time only in the text field in HTML using JavaScript but its not showing. Kindly help me out.
<input type="text" name="time1" id="e1" value="" />
<script>
function display_ct() {
var strcount
var x = new Date()
var x1=x.getMonth() + "/" + x.getDate() + "/" + x.getYear();
x1 = x1 + " - " + x.getHours( )+ ":" + x.getMinutes() + ":" + x.getSeconds();
//document.getElementById('ct').innerHTML = x1;
//tt=display_c();
document.getElementById('e1').value = x1;
}
</script>
All you need to do is call your function.
HTML
<input type="text" name="time1" id="e1" value="" />
JavaScript
function display_ct() {
var strcount
var x = new Date()
var x1=x.getMonth() + "/" + x.getDate() + "/" + x.getYear();
x1 = x1 + " - " + x.getHours( )+ ":" + x.getMinutes() + ":" + x.getSeconds();
//document.getElementById('ct').innerHTML = x1;
//tt=display_c();
document.getElementById('e1').value = x1;
}
display_ct();
JSFiddle
http://jsfiddle.net/aGGHQ/
getYear is no longer used and has been replaced by the getFullYear method.
var x1=x.getMonth() + "/" + x.getDate() + "/" + x.getFullYear();