Arithmetic expressions in Javascript - javascript

I have studied java and php for many years and recently just started developing in JavaScript as well. Anyway a fairly noob question but can anyone work out why this application isn't showing displaying the interest when the button is clicked? I have been using w3schools website to learn from.
code:
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Interest Calculator</title>
</head>
<body>
<fieldset>
<legend>Interest Calculator</legend>
Enter amount: <input type="text" id="amount" ><br><br>
Interest rate: <input type="text" id="interest"><br><br>
Enter years: <input type="text" id="years"><br><br>
<button onclick="calculate()">Calculate</button>
</fieldset>
<p id="sum"></p>
<script>
function calculate(){
var amount = document.getElementById("amount").value;
var rate = document.getElementById("interest").value;
var years = document.getElementById("years").value;
var sum = amount(1+rate)^years;
var message = "Your total return will be: " + sum;
document.getElementById("sum").innerHTML = message;
}
</script>
</body>
</html>
Many thanks,
Adam

You need to explicitly specify *. It is not normal for 5(3) = 15 in JavaScript or any programming language. You need to explicitly specify 5*(3):
var sum = amount*(1+rate)^years;
Working Code
<fieldset>
<legend>Interest Calculator</legend>
Enter amount: <input type="text" id="amount" ><br><br>
Interest rate: <input type="text" id="interest"><br><br>
Enter years: <input type="text" id="years"><br><br>
<button onclick="calculate()">Calculate</button>
</fieldset>
<p id="sum"></p>
<script>
function calculate(){
var amount = document.getElementById("amount").value;
var rate = document.getElementById("interest").value;
var years = document.getElementById("years").value;
var sum = amount*(1+rate)^years;
var message = "Your total return will be: " + sum;
document.getElementById("sum").innerHTML = message;
}
</script>
Fiddle: http://jsbin.com/lovevazaxe

The OP uses the ^ operator and presumably wants to use the power-of operator.
In javascript the ^ operator refers to bitwise XOR - I don't think that's what the OP wants.
Instead, the power-of operation is done with the Math.pow() function.
So replace var sum = amount(1+rate)^years; with
var sum = Math.pow(amount*(1+rate),years)

Related

Basic math functions in JavaScript to show on HTML page

I would like to make major of basic math functions (addition, subtraction, ect.) to develop in JavaScript. Input parameters should be from HTML webpage, than do the in JavaScript and return result on the same HTML page.
function math() {
//document.getElementById("frm1").innerHTML;
var numb = document.getElementById("number").innerHTML;
var mod = document.getElementById("modifier").innerHTML;
console.log(numb);
console.log(mod);
var sum = 1; //numb + mod; //the 1 is a placeholder
console.log(sum);
sum = document.getElementById("sum").innerHTML;
}
<form id="frm1" action="randScript.js">
Number: <input type="int" name="number" id="number"><br> Modifiers: <input type="int" name="modifier" id="modifier"><br>
<input type="button" onclick="math()" value="Submit">
</form>
<p id="sum"></p>
Your form tag has an action attribute. This means the page will submit your information to the specified page. You can use jQuery to prevent the form from submitting.
$("#yourFormId").on("submit",function(event){event.preventDefault()})
You can also edit the forms action attribute itself to prevent it from submitting.
<form id="frm1" action"javascript:void(0);">
First: The type is text - there is no "int" thing
Number: <input type="text" name="number" id="number">
Second: if we read a bit documentation we figure also out how to get the alue into the JS part
var numb = document.getElementById("number").value;
here you can now do your further homework ;)
Third: Get things back:
either use another input. They work two ways.
document.getElementById("result").value="I did not do my homework alone"
or you place a div somewhere with an id
<div id="result"> </div>
and now you can really use innerHTML in js
document.getElementById("result").innerHTML="I am too lazy";
The rest and to put it all together is now up to you :) Have fun to study :)
Try that if you want to display the sum at the html element:
document.getElementById("sum").innerHTML = sum;
But a more precise Question would help!
There is no int type for form inputs in HTML you can learn here about input types: HTML form input types
<form id="frm1" >
Number1: <input type="number" name="number" id="number1"><br>
Number2: <input type="number" name="number" id="number2"><br>
Modifiers: <input type="text" name="modifier" id="modifier"><br>
<input type="button" onclick="math()" value="Submit">
</form>
<p id = "sum"></p>
<script type="text/javascript">
function math() {
var numb1 = parseInt(document.getElementById("number1").value);
var numb2 = parseInt(document.getElementById("number2").value);
var mod = document.getElementById("modifier").value;
if(mod == '+'){
var sum = numb1 + numb2;
}else if(mod == '-'){
var sum = numb1 - numb2;
}else if(mod == '*'){
var sum = numb1 * numb2;
}
if(sum === undefined){
alert('invalid inputs');
return false;
}else{
document.getElementById("sum").innerHTML = sum;
}
return true;
}
To retrieve inputs values properly use value rather then innerHtml.
Retrieved values are strings so you need to parse them to numbers (with parseInt) before using them in math.
function math() {
const numb = document.getElementById("number").value;
const mod = document.getElementById("modifier").value;
sum = document.getElementById("sum").innerText = parseInt(numb) + parseInt(mod);
}

Simple time and half calculator in JavaScript

I have made a simple time and half calculator in HTML and JavaScript, but for some reason, when I click the Calculate button, the P element does not show the result.
Here is my code:
http://codepen.io/chrissylvester10/pen/wJxder
html>
<head>
</head>
<body>
<h1>Time and Half Calculator</h1>
<input id="fare" size="7" maxlength="7" name="fare" style="width:75px" value="0" />
<input type="button" value="Calculate" onclick="calculator()">
<p id="result"></p>
</body>
</html>
var fare = document.getElementById("#fare").value;
function calculator() {
var result = fare / 2 + fare;
document.getElementById("result").innerHTML = result;
}
Please fork it because I need to see the changes.
First thing, you don't need the # in var fare = document.getElementById("#fare").value;.
It should be var fare = document.getElementById("fare").value;
That line of code should also be inside the function, so it will read the new value every time you change it, otherwise, it will just return 0.
Lastly, you want to parse the number so it isn't misread as a string.
function calculator() {
var fare = parseInt(document.getElementById("fare").value);
var result = fare / 2 + fare;
document.getElementById("result").innerHTML = result;
}
edit:
A much simpler way to do this would be
function calculator() {
document.getElementById("result").innerHTML = document.getElementById("fare").value*1.5;
}
You are getting the value at the start and not the actual value.
Solution: Move the fare declaration inside of the function.
Small change: Get only fare as id.
function calculator() {
var fare = +document.getElementById("fare").value,
result = fare / 2 + fare;
document.getElementById("result").innerHTML = result;
}
<h1>Time and Half Calculator</h1>
<input id="fare" size="7" maxlength="7" name="fare" style="width:75px" value="0" />
<input type="button" value="Calculate" onclick="calculator()">
<p id="result"></p>
What about to enclose your Javascript into <script> tags?
And remove # from fare.

javascript calculator works only after refreshing the page

I made this calculator http://fernandor80.neocities.org/plancalc/tomx2.html
and it always returns Nan, but once you reload it (with the previously entered inputs), it works...
I've been looking around but I can not figure it out... So I'm here because I really want to get it to work.
here is the code to it:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Plant Calc V1.2</title>
<link rel="stylesheet" href="main.css">
</head>
<body>
<main>
<form name="plantrow" method=POST>
<h1>How many trays per round?</h1>
<input type="text" id="ppr">
<br>
<h1>How many rows (6,10,12)?</h1>
<input type="text" id="bed">
<input type="button" id="firstcalc" value="go!" onClick="row()">
</form>
<br>
<h2>Trays per row::</h2>
<h1 id="ppb"></h1>
<form name="field" method=POST>
<h1>Total rows in the field??</h1>
<input type="text" id="totalb">
<input type="button" id="secondcalc" value="go!" onClick="total()">
</form>
<h1>You need:::</h1>
<h1 id="totalp"></h1>
<h1>trays</h1>
<div id="bins">
45 count bins<h2 id="bin45"></h2>
90 count bins<h2 id="bin90"></h2>
</div>
<form name="nowplants" method=POST>
<h1> How much plant you have now(trays)???</h1>
<input type="text" id="nowp">
<input type="button" id="thirdcalc" value="go" onClick="now()">
</form>
<h1>You can plant ::</h1>
<h1 id="nowb"></h1>
<h1>rows</h1>
</main>
<script language="JavaScript">
var ppr = parseFloat(document.getElementById("ppr").value);
var bed = parseFloat(document.getElementById("bed").value);
var ppb = ppr/bed ;
var totalb = parseFloat(document.getElementById("totalb").value);
var totalp = totalb * ppb;
var bin45 = totalp/45 ;
var bin90 = totalp/90 ;
var nowp = document.getElementById("nowp").value;
var nowb = nowp/ppb ;
function row(){
document.getElementById("ppb").innerHTML = ppb;
}
function total(){
document.getElementById("totalp").innerHTML = totalp;
document.getElementById("bin45").innerHTML = bin45;
document.getElementById("bin90").innerHTML = bin90;
}
function now(){
document.getElementById("nowb").innerHTML = nowb;
}
</script>
</body>
</html>
Also it doesnt work on mobile devices..I made a pure javascript prompt based calculator for that, but for the purpose of learning i would like some pointers.
I really feel bad about asking a question thats been answered hundreds of times. Sorry, I just had to..
the values of ppr, bed, and ppb are calculated when the page first loads. Thus it's a NaN.
You should consider move at least the data retrieval and calculation inside function row().
One simple way to debug issue like this, if you don't use any IDE, it to press f12 in your browser and open dev mode where you can set break point and check the current value of your variables.
You have dependency over other variable in every function. Instead of using global variables, you can access value in each function.
function row() {
var ppr = parseFloat(document.getElementById("ppr").value);
var bed = parseFloat(document.getElementById("bed").value);
var ppb = ppr / bed;
document.getElementById("ppb").innerHTML = ppb;
}
function total() {
var ppr = parseFloat(document.getElementById("ppr").value);
var bed = parseFloat(document.getElementById("bed").value);
var ppb = ppr / bed;
var totalb = parseFloat(document.getElementById("totalb").value);
var totalp = totalb * ppb;
var bin45 = totalp / 45;
var bin90 = totalp / 90;
document.getElementById("totalp").innerHTML = totalp;
document.getElementById("bin45").innerHTML = bin45;
document.getElementById("bin90").innerHTML = bin90;
}
function now() {
var ppr = parseFloat(document.getElementById("ppr").value);
var bed = parseFloat(document.getElementById("bed").value);
var ppb = ppr / bed;
var totalb = parseFloat(document.getElementById("totalb").value);
var totalp = totalb * ppb;
var bin45 = totalp / 45;
var bin90 = totalp / 90;
var nowp = document.getElementById("nowp").value;
var nowb = nowp / ppb;
document.getElementById("nowb").innerHTML = nowb;
}
<main>
<form name="plantrow" method=POST>
<h1>How many trays per round?</h1>
<input type="text" id="ppr">
<br>
<h1>How many rows (6,10,12)?</h1>
<input type="text" id="bed">
<input type="button" id="firstcalc" value="go!" onClick="row()">
</form>
<br>
<h2>Trays per row::</h2>
<h1 id="ppb"></h1>
<form name="field" method=POST>
<h1>Total rows in the field??</h1>
<input type="text" id="totalb">
<input type="button" id="secondcalc" value="go!" onClick="total()">
</form>
<h1>You need:::</h1>
<h1 id="totalp"></h1>
<h1>trays</h1>
<div id="bins">
45 count bins
<h2 id="bin45"></h2>
90 count bins
<h2 id="bin90"></h2>
</div>
<form name="nowplants" method=POST>
<h1> How much plant you have now(trays)???</h1>
<input type="text" id="nowp">
<input type="button" id="thirdcalc" value="go" onClick="now()">
</form>
<h1>You can plant ::</h1>
<h1 id="nowb"></h1>
<h1>rows</h1>
</main>
It will always NaN because your call values of ppr, bed, and ppb when just first page loaded ! At that page loaded time ,you didn't have any value so NaN getting.So when you click ,you should call that value again ,make it function to call values will be more better...
here I push init() to get value onclick
<script type="text/javascript">
var ppr,bed,ppb,totalp,totalb,bin45,bin90,nowb,nowb;
function init(){
ppr = parseFloat(document.getElementById("ppr").value);
bed = parseFloat(document.getElementById("bed").value);
ppb = ppr/bed ;
totalb = parseFloat(document.getElementById("totalb").value);
totalp = totalb * ppb;
bin45 = totalp/45 ;
bin90 = totalp/90 ;
nowp = document.getElementById("nowp").value;
nowb = nowp/ppb ;
}
function row(){
init();
document.getElementById("ppb").innerHTML = ppb;
}
</script>

"NaN" result when multiplying more than one value in an array by a number

Note: please pay no attention to my beginnings on the "Decrypt" function, button, etc. It has no relevance towards this question.
I've looked practically everywhere for a fix on here and can't seem to find one due to my kinda strange project. I'm a noob at JavaScript so please tell me anything I could improve on. Here's my project: It's basically a Encrypt/Decrypt message thing based on what key you type in.. When you type in the key, and submit it, it gives the key a value based on it's length and ASCII value:
function submitkey(form) {
keyinp = (form.key.value)
var keyl = keyinp.length
keyasciiout = keyinp.charCodeAt(0)
document.getElementById("asciikeyout").innerHTML =
"<b>" + keyinp + "</b> is your key."
if (keyl > 4) {
keyasciitwo = keyinp.charCodeAt(1)
keyasciithree = keyinp.charCodeAt(2)
keyasciifour = keyinp.charCodeAt(3)
keyasciifive = keyinp.charCodeAt(4)
finalkey = (((keyasciiout + keyasciitwo + keyasciithree + keyasciifour + keyasciifive) / keyl) * 0.5)
}
else { alert("Please choose a new key. It must be 5 or more characters.") }
}
So now you've entered a key and it has a value that plays a role in encrypting/decrypting your messages. Here's the text boxes that you enter in and stuff.
<form name="keyinput">
<input type="text" id="key" name="key">
<br>
<input type="button" name="keysub" id="keysub" value="Submit Key" onclick="submitkey(this.form)">
</form>
<p id="asciikeyout"></p>
<p id="key2"></p>
<br> <br>
<br> <br>
<br> <br>
<form name="field">
<input type="button" name="decryptbutton" onclick="dec(this.form)" value="Decrypt">
<br>
<textarea id="input" rows="4" cols="50" onkeyup="getascii(this.form)" onkeydown="keycheck(this.form)"></textarea>
<br>
<br>
<textarea id="output" rows="20" cols="70" fontsize="18px" readonly></textarea>
</form>
<p id="res2"></p>
By the way, the keycheck() function is just something where if you type in the textbox and don't have anything entered as a key, it will alert you to create a key.
So whenever you type into the input textbox, it runs getascii(this.form), which, btw, just gets the ASCII values of all of the characters you typed and stores them as a variable, in which this case, is "code":
function getascii(form) {
globalinp=(form.input.value)
var str=(form.input.value);
code = new Array(str.length);
for(var i=0;i<str.length;i++){
code[i]=str.charCodeAt(i);
}
encrypt(code)
}
Which, in turn, runs encrypt(), which places the "code" values into an array(i think, this may be the issue. please tell me.):
function encrypt(code) {
sepcode = code.toString().replace(/,/g, " ")
asciiarray = sepcode.split(" ");
arrmult()
}
Which, then again, runs a function called arrmult, which is where the trouble begins (i think).
function arrmult() {
var a = [asciiarray];
var b = a.map((function (x) { return x * finalkey; }).bind(this));
document.getElementById("output").innerHTML =
b
}
The above code I got from this website. What it does is takes each individual value of the array assigned as the variable A, in this case all of the ASCII values of whatever you typed in the box, and multiplies them by a certain value, which I have set as the value of the key. Note: When I replace the variable A with a string of numbers, like this:
var a = [127,93,28];
It seems to be working perfectly fine. But, when I use asciiarray instead, it returns back with a value of "NaN", but only when I do more than ONE character. When I only type one character and have the variable a set as this:
var a = [asciiarray];
It works perfectly fine. But when it updates, and has two or more characters, it results as "NaN" even though the value of asciiarray is the exact same as the numbers above. And when you do reply, please help me realize where to replace what I've done wrong, as I'm a JavaScript complete noob.
If you wish to look at the code completely, here it is. You can even copy and paste it into an HTML file if you wish:
<html>
<body>
<head>
<title>Ascii Encryption</title>
</head>
<script>
var code="test"
var sepcode="test"
var keyinp="test"
var keyasciiout="test"
var finalkey="test"
var globalinp="test"
var globalascarr="test"
var multex="test"
var keyasciitwo="test"
function getascii(form) {
globalinp=(form.input.value)
var str=(form.input.value);
code = new Array(str.length);
for(var i=0;i<str.length;i++){
code[i]=str.charCodeAt(i);
}
encrypt(code)
}
</script>
<script>
function submitkey(form) {
keyinp = (form.key.value)
var keyl = keyinp.length
keyasciiout = keyinp.charCodeAt(0)
document.getElementById("asciikeyout").innerHTML =
"<b>" + keyinp + "</b> is your key."
if (keyl > 4) {
keyasciitwo = keyinp.charCodeAt(1)
keyasciithree = keyinp.charCodeAt(2)
keyasciifour = keyinp.charCodeAt(3)
keyasciifive = keyinp.charCodeAt(4)
finalkey = (((keyasciiout + keyasciitwo + keyasciithree + keyasciifour + keyasciifive) / keyl) * 0.5)
}
else { alert("Please choose a new key. It must be 5 or more characters.") }
}
</script>
<script>
function encrypt(code) {
sepcode = code.toString().replace(/,/g, " ")
asciiarray = sepcode.split(" ");
arrmult()
}
</script>
<script>
function arrmult(none) {
var a = [asciiarray];
var b = a.map((function (x) { return x * finalkey; }).bind(this));
document.getElementById("output").innerHTML =
b
}
</script>
<script>
function dec(form) {
var input = (form.input.value)
var inputdiv = (input / finalkey)
var decrypted = String.fromCharCode(inputdiv)
alert(decrypted)
}
</script>
<script>
function keycheck(form) {
if (finalkey != null) {
null
} else {
alert("Please enter a key. This will determine how your encryptions and decryptions are made.")
}
}
</script>
<center>
<br> <br>
<br> <br>
<form name="keyinput">
<input type="text" id="key" name="key">
<br>
<input type="button" name="keysub" id="keysub" value="Submit Key" onclick="submitkey(this.form)">
</form>
<p id="asciikeyout"></p>
<p id="key2"></p>
<br> <br>
<br> <br>
<br> <br>
<form name="field">
<input type="button" name="decryptbutton" onclick="dec(this.form)" value="Decrypt">
<br>
<textarea id="input" rows="4" cols="50" onkeyup="getascii(this.form)" onkeydown="keycheck(this.form)"></textarea>
<br>
<br>
<textarea id="output" rows="20" cols="70" fontsize="18px" readonly></textarea>
</form>
<p id="res2"></p>
</center>
</body>
</html>

How to write to page in java script DOm model

I am doing a java script application that calculates Miles driven / gallons used and gallons used* price per gallon. I have two problems:
1) when I enter all the values price per gallon adds a another zero automatically. For example 40, becomes 400.
2) I am looking to write the result of both calculations underneath the button.
If anyone can give me guidance or help I would really appreciate it.
<!DOCTYPE
<html>
<head>
<meta charset="utf-8">
<title> MPG application </title>
<script>
var $ = function(id) {
return document.getElementById(id);
}
/* the user entries will be parsed floats and a if
statment is checking to see if the person enters not #*/
var calculateMpg = function () {
var miles = parseFloat($("miles").value); //alert(miles);
var gallons = parseFloat($("gallons").value);
var costGallon = document.getElementById("costGallon").value;
if (isNaN(miles) || isNaN(gallons)) {
alert("enter a valid number");
}
else {
var mpg = miles/gallons;
var costGallon = gallons*costGallon;
$("costGallon").value=costGallon.toFixed(2);
//alert("your total is" +mpg );
alert("your total new is " + costGallon);
//cost of trip = gallons used * price per gallon
}
}
//write to the page
window.onload = function () {
$("calculate").onclick = calculateMpg;
//focues means brings the window to the front
$("costGallon").focus();
}
</script>
</head>
<section>
<body>
<h1> calculate mPG </h1>
<p>Enter the information below</p>
<label for="miles">Miles Driven: </label>
<!--the code under gives a form box of text-->
<input type="text" id="miles"> <br><br>
<label for = "gallons"> Gallons of gas used :</label>
<input = "text" id="gallons"><br><br>
<label for = "costGallon"> Price per Gallon: </label>
<input = "text" id="costGallon" ><br><br>
<label> </label>
<input type = "button" id = "calculate" value = "Calculate MPG and cost of the trip">
<!-- So here I want to say your mpg is and then call mpg. which I thought I did in the top abobe window.onload -->
<p style="color: red"> Your mpg is: <span id = "totalMpg"> </span>
</section>
</body>
</html>
Can you give me an example of where it does that? I copy pasted your code and for me it gives the correct values. From what I understand the only thing you are writting into the cost per gallon field is the gallons used times the price per gallon. An that seems to be working fine.
If you can provide me with a example calculation you want to achive i'd be happy to help.
On another note, i suggest not using the same variable again in line 27 that you used to hold the DOM object of the input field. Also toFixed does not change the variable you used it on but return a new variable so instead remove that in line 28 and have line 27 look something like this:
var newVarNameIsBoss = (gallons*costGallon).toFixed(2);
Hope this helps
revised code
<!DOCTYPE html> <!-- scorrect doctype-->
<html>
<head>
<meta charset="utf-8">
<title> MPG application </title>
<script>
var $ = function(id) {
return document.getElementById(id);
};//remember that a var decleration always ends with a ; even if it's a function
/* the user entries will be parsed floats and a if
statment is checking to see if the person enters not #*/
var calculateMpg = function () {
var miles = parseFloat($("miles").value), //alert(miles);
gallons = parseFloat($("gallons").value),
costGallon = document.getElementById("costGallon").value,
mpg,totalCost;
if (isNaN(miles) || isNaN(gallons)) {
alert("enter a valid number");
} else {
mpg = miles/gallons;
totalCost = (gallons*costGallon).toFixed(2);
costGallon.value=totalCost;
alert("your total new is " + totalCost);
$('totalMpg').innerHTML = String(mpg.toFixed(2)) + " Miles per Gallon";
}
};//remember that a var decleration always ends with a ; even if it's a function
//write to the page
window.onload = function () {
$("calculate").onclick = calculateMpg;
//focues means brings the window to the front
$("costGallon").focus();
};//remember that a var decleration always ends with a ; even if it's a function
</script>
</head>
<body>
<section> <!-- section bellow the body tag-->
<h1> calculate mPG </h1>
<p>Enter the information below</p>
<label for="miles">Miles Driven: </label>
<!--the code under gives a form box of text-->
<input type="text" id="miles"> <br/><br/>
<label for = "gallons"> Gallons of gas used :</label>
<input = "text" id="gallons"><br/><br/>
<label for = "costGallon"> Price per Gallon: </label>
<input = "text" id="costGallon" ><br/><br/>
<label> </label>
<input type = "button" id = "calculate" value = "Calculate MPG and cost of the trip">
<!-- So here I want to say your mpg is and then call mpg. which I thought I did in the top abobe window.onload -->
<p style="color: red"> Your mpg is: <span id = "totalMpg"> </span></p><!--closing p tag here-->
</section>
</body>
</html>

Categories

Resources