Conversion between different versions of BT.601,BT.709 and RGB - javascript

Since the color-space conversion confused me ago, I have created this tool to easy conversion between different versions of BT.601,BT.709 and RGB.
But I still not sure if I should use floor or round to calculate the conversion result. please help comment then I will improve this tool.
A601v1 = [[0.257, 0.504, 0.098],
[-0.148, -0.291, 0.439],
[0.439, -0.368, -0.071]];
O601v1 = [[16, 128, 128]];
A601v2 = [[0.299, 0.587, 0.114],
[-0.173, -0.339, 0.511],
[0.511, -0.428, -0.083]];
O601v2 = [[16, 128, 128]];
A601v3 = [[0.299, 0.587, 0.114],
[-0.169, -0.331, 0.500],
[0.500, -0.419, -0.081]];
O601v3 = [[0, 128, 128]];
A709v1 = [[0.1826, 0.6142, 0.0620],
[-0.1006, -0.3386, 0.4392],
[0.4392, -0.3989, -0.0403]];
O709v1 = [[16, 128, 128]];
A709v2 = [[0.2126, 0.7152, 0.0722],
[-0.1146, -0.3854, 0.5000],
[0.5000, -0.4542, -0.0468]];
O709v2 = [[0, 128, 128]];
A = A601v1;
O = O601v1;
function combo(thelist) {
var idx = thelist.selectedIndex;
var colspace = thelist.options[idx].value;
if (colspace === "BT.601v1") {
A = A601v1;
O = O601v1;
}else if (colspace === "BT.601v2") {
A = A601v2;
O = O601v2;
}else if (colspace === "BT.601v3") {
A = A601v3;
O = O601v3;
}else if (colspace === "BT.709v1") {
A = A709v1;
O = O709v1;
}else if (colspace === "BT.709v2") {
A = A709v2;
O = O709v2;
}
}
function yuv2rgb(f) {
var y, u, v,r,g,b, yuv,rgb,offset;
y = parseInt(f.y.value);
u = parseInt(f.u.value);
v = parseInt(f.v.value);
yuv = [[y,u,v]];
Ainv = math.inv(A);
yuv = math.subtract(yuv,O);
rgb = math.multiply(yuv,math.transpose(Ainv))
rgb = math.round(rgb);
rgb = clip(rgb,0,255);
r = rgb[0][0];
g = rgb[0][1];
b = rgb[0][2];
f.red.value = r;
f.green.value = g;
f.blue.value = b;
var yuvElem = document.getElementById('yuv');
yuvElem.src = getDataUrl(r,g,b);
}
function rgb2hex(r,g,b) {
var v;
if (g !== undefined) {
v = Number(0x1000000 + r*0x10000 + g*0x100 + b).toString(16).substring(1);
}else {
v = Number(0x1000000 + r[0][0]*0x10000 + r[0][1]*0x100 + r[0][2]).toString(16).substring(1);
}
return "#" + v;
}
function clip(m1,low,high) {
var result = [];
for (var i = 0; i < m1.length; i++) {
result[i] = [];
for (var j = 0; j < m1[0].length; j++) {
if (m1[i][j] < low) {
result[i][j] = low;
}else if (m1[i][j] > high) {
result[i][j] = high;
}else{
result[i][j] = m1[i][j];
}
}
}
return result;
}
function rgb2yuv(f) {
var y, u, v, r, g, b,yuv,rgb,offset;
r = parseInt(f.red.value);
g = parseInt(f.green.value);
b = parseInt(f.blue.value);
rgb = [[r,g,b]];
yuv = math.multiply(rgb,math.transpose(A));
yuv = math.add(yuv,O);
yuv = math.round(yuv);
yuv = clip(yuv,0,255);
f.y.value = yuv[0][0];
f.u.value = yuv[0][1];
f.v.value = yuv[0][2];
var yuvElem = document.getElementById('yuv');
yuvElem.src = getDataUrl(r,g,b);
}
function getDataUrl(r,g,b) {
var canvas = document.createElement('canvas');
var height=100;
var width=100;
canvas.height=height;
canvas.width=width;
var context = canvas.getContext("2d");
var imageData=context.createImageData(width, height);
var data = imageData.data;
for (var i=0; i<height*width; i++) {
data[i*4+0] = r | 0;
data[i*4+1] = g | 0;
data[i*4+2] = b | 0;
data[i*4+3] = 255;
}
context.putImageData(imageData, 0, 0);
var url = canvas.toDataURL("image/png");
return url;
}
<!DOCTYPE html>
<html>
<head>
<title>yuv rgb converter</title>
</head>
<body>
<form name="yuv2rgb_form">
<label for="colspace">Color space:</label>
<select name="colspace" onChange="combo(this)">
<option>BT.601v1</option>
<option>BT.601v2</option>
<option>BT.601v3</option>
<option>BT.709v1</option>
<option>BT.709v2</option>
</select>
<table border="1">
<tr>
<td>
<table border="0">
<tr>
<td>Red</td>
<td><input type="text" name="red" value="0" size=5></td>
</tr>
<tr>
<td>Green</td>
<td><input type="text" name="green" value="0" size=5></td>
</tr>
<tr>
<td>Blue</td>
<td><input type="text" name="blue" value="0" size=5></td>
</tr>
<tr>
<td><input type="button" value="rgb2yuv" onclick="rgb2yuv(this.form);"></td>
</tr>
</table>
</td>
<td>
<table>
<tr>
<td>Y</td>
<td><input type="text" name="y" value="0" size=5></td>
</tr>
<tr>
<td>U</td>
<td><input type="text" name="u" value="0" size=5></td>
</tr>
<tr>
<td>V</td>
<td><input type="text" name="v" value="0" size=5></td>
</tr>
<tr>
<td><input type="button" value="yuv2rgb" onclick="yuv2rgb(this.form);"></td>
</tr>
</table>
</td>
<td><Image id="yuv" style="width:100px; height:100px;"></div></td>
</tr>
</table>
</form>
</body>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/mathjs/3.2.1/math.js"></script>
</html>

Related

Weapon damage range calculator no error but it's not working

Because I'm too lazy to calculate every time I decided to make a calculator with jquery.
For some reason it's not working and I don't know why so I'm here to ask you guys for help.
Here's a jsfiddle link
Damage Formula:
AbaseEq: Damage Range of weapon (e.g: 800~1000)
up difference: weapon up- armor up (e.g: 5-3:2 -> up difference:2 -> 15% if difference was 1 it would be 10%)
Aeq: AbaseEq(1+up difference in %)
Codes:
<table>
<tr>
<td>
<label>Base Attack (Without any equipment equipped): </label>
</td>
<td>
<input placeholder="e.g: 290" id="abase">
</td>
</tr>
<tr>
<td>
<label>Weapon Attack Range: </label>
</td>
<td>
<input placeholder="e.g: 800-1000" id="abaseeq">
</td>
</tr>
<tr>
<td>
<label>Weapon + ?</label>
</td>
<td>
<input placeholder="e.g: 9" id="weapon+">
</td>
</tr>
<tr>
<td>
<label>Enemy Defence + ? </label>
</td>
<td>
<input placeholder="e.g: 6" id="enemydef+">
</td>
</tr>
<tr>
<td>
<button id="calculate">
Calculate
</button>
</td>
<td>
<div id="result"></div>
</td>
</tr>
</table>
$(document).ready(function() {
$('#calculate').on('click', function() {
var abase = $('#abase').val();
var abaseEq = $('#abaseeq').val();
var abaseEqLength = abaseEq.length;
abaseEqLength -= 1;
var weaponlvl = $('#weaponup').val();
var enemydeflvl = $('#enemydefup').val();
var weaponup=parseInt(weaponlvl);
var enemydefup=parseInt(enemydeflvl);
var updifference = weaponup - enemydefup;
var plusdifference = [0, '10%', '15%', '22%', '32%', '43%', '54%', '65%', '90%', '120%', '200%'];
var negdifference = {};
var result;
var aeqmin=0;
var aeqmax=0;
var lowestdamage="";
var maxdamage="";
var negindex;
var negindexplus = 0;
for (var i = 0; i <= abaseEqLength; i++) {
if (abaseEq[i] == '-') {
negindex = i;
negindexplus += (negindex + 1);
}
}
for (var x = 0; x < negindex; x++) {
lowestdamage = lowestdamage + abaseEq[x];
console.log("Lowest Damage: " + lowestdamage);
}
for (var y = negindexplus; y <= abaseEqLength; y++) {
maxdamage = maxdamage + abaseEq[y];
console.log("Max Damage: " + maxdamage);
}
if (updifference => 0 && updifference <= 10) {
updifference = plusdifference[updifference];
console.log("updifference: "+updifference);
result = "pos";
}
if (updifference < 0 && updifference >= -10) {
var negarray = negdifference * -1;
negdifference[updifference] = plusdifference[negarray];
}
var mindamage = parseInt(lowestdamage);
var maxidamage = parseInt(maxdamage);
if (result == "pos") {
aeqmin = mindamage * (1 + plusdifference[updifference]);
aeqmax = maxidamage * (1 + plusdifference[updifference]);
}
if (aeqmax > 0) {
$('#result').html = aeqmin + "~" + aeqmax;
}
}); // calculate on click function
}); // document ready

JavaScript GPA calculator isn't reading user inputs

I'm a beginner to JavaScript. Here I can't figure out why my code isn't reading the values which I input, even-though I can't find out any errors in my code. Any helpful suggestions to edit my code to fix the error?
function gpacalc() {
//define valid grades and their values
var gr = new Array(6);
var cr = new Array(6);
var ingr = new Array(5);
var incr = new Array(5);
// define valid grades and their values
var grcount = 11;
gr[0] = "A+";
cr[0] = 4;
gr[1] = "A";
cr[1] = 4;
gr[2] = "A-";
cr[2] = 3.70;
gr[3] = "B+";
cr[3] = 3.30;
gr[4] = "B";
cr[4] = 3;
gr[5] = "B-";
cr[5] = 2.70;
gr[6] = "C+";
cr[6] = 2.30;
gr[7] = "C";
cr[7] = 2;
gr[8] = "C-";
cr[8] = 1.70;
gr[9] = "D";
cr[9] = 1;
gr[10] = "D-";
cr[10] = 0.70;
// retrieve user input
ingr[0] = document.GPACalcForm.GR1.value;
ingr[1] = document.GPACalcForm.GR2.value;
ingr[2] = document.GPACalcForm.GR3.value;
ingr[3] = document.GPACalcForm.GR4.value;
ingr[4] = document.GPACalcForm.GR5.value;
incr[0] = document.GPACalcForm.CR1.value;
incr[1] = document.GPACalcForm.CR2.value;
incr[2] = document.GPACalcForm.CR3.value;
incr[3] = document.GPACalcForm.CR4.value;
incr[4] = document.GPACalcForm.CR5.value;
// Calculate GPA
var allgr = 0;
var allcr = 0;
var gpa = 0;
for (var x = 0; x < 5; x++) {
if (ingr[x] == "")
break;
alert("Error: You did not enter a numeric credits value for subject. If the subject is worth 0 credits, then enter the number 0 in the field.");
var validgrcheck = 0;
for (var xx = 0; xx < grcount; xx++) {
if (ingr[x] == gr[xx]) {
allgr = allgr + (parseInt(incr[x], 10) * cr[xx]);
allcr = allcr + parseInt(incr[x], 10);
validgrcheck = 1;
break;
}
}
if (validgrcheck == 0) {
alert("Error: Could not recognize the grade entered for subject " + eval(x + 1) + ". Please use standard college grades in the form of A+, A, B+ ... D-");
return 0;
}
}
if (allcr == 0) {
alert("Error:You did not enter any credit values. GPA = N/A");
return 0;
}
gpa = allgr / allcr;
alert("GPA = " + gpa);
return 0;
}
<center>
<form name="GPACalcForm">
<table border="2" bgcolor="#bb8fce" cellpadding="5" cellspacing="2">
<TH> </TH>
<TH>Grade</TH>
<TH>Credits</TH>
<TR>
<TD>IT 201</TD>
<TD><input type="text" size="5" name="GR1" align="top" maxlength="5"></TD>
<TD><input type="text" size="5" name="CR1" align="top" maxlength="5"></TD>
</TR>
<TR>
<TD>IT 202</TD>
<TD><input type="text" size="5" name="GR2" align="top" maxlength="5"></TD>
<TD><input type="text" size="5" name="CR2" align="top" maxlength="5"></TD>
</TR>
<TR>
<TD>IT 203</TD>
<TD><input type="text" size="5" name="GR3" align="top" maxlength="5"></TD>
<TD><input type="text" size="5" name="CR3" align="top" maxlength="5"></TD>
</TR>
<TR>
<TD>IT 204</TD>
<TD><input type="text" size="5" name="GR4" align="top" maxlength="5"></TD>
<TD><input type="text" size="5" name="CR4" align="top" maxlength="5"></TD>
</TR>
<TR>
<TD>IT 205</TD>
<TD><input type="text" size="5" name="GR5" align="top" maxlength="5"></TD>
<TD><input type="text" size="5" name="CR5" align="top" maxlength="5"></TD>
</TR>
<TR>
<TR align="center">
<TD colspan="3">
<input type="button" value="Calculate" name="CalcButton" OnClick="gpacalc()">
</TD>
</TR>
</table>
</form>
<br/>
<p> </p>
</center>
<br/>
I'm a beginner to JavaScript. Here I can't figure out why my code isn't reading the values which I input, even-though I can figure out any errors in my code. Any helpful suggestions to edit my code to fix the error?
function gpacalc()
{
//define valid grades and their values
var gr = new Array(6);
var cr = new Array(6);
var ingr = new Array(5);
var incr = new Array(5);
// define valid grades and their values
var grcount = 11;
gr[0] = "A+";
cr[0] = 4;
gr[1] = "A";
cr[1] = 4;
gr[2] = "A-";
cr[2] = 3.70;
gr[3] = "B+";
cr[3] = 3.30;
gr[4] = "B";
cr[4] = 3;
gr[5] = "B-";
cr[5] = 2.70;
gr[6] = "C+";
cr[6] = 2.30;
gr[7] = "C";
cr[7] = 2;
gr[8] = "C-";
cr[8] = 1.70;
gr[9] = "D";
cr[9] = 1;
gr[10] = "D-";
cr[10] = 0.70;
// retrieve user input
ingr[0] = document.GPACalcForm.GR1.value;
console.log(ingr[0]);
ingr[1] = document.GPACalcForm.GR2.value;
ingr[2] = document.GPACalcForm.GR3.value;
ingr[3] = document.GPACalcForm.GR4.value;
ingr[4] = document.GPACalcForm.GR5.value;
incr[0] = document.GPACalcForm.CR1.value;
incr[1] = document.GPACalcForm.CR2.value;
incr[2] = document.GPACalcForm.CR3.value;
incr[3] = document.GPACalcForm.CR4.value;
incr[4] = document.GPACalcForm.CR5.value;
// Calculate GPA
var allgr = 0;
var allcr = 0;
var gpa = 0;
for (var x = 0; x < 5; x++)
{
if (ingr[x] == "") {
alert("Error: You did not enter a numeric credits value for subject. If the subject is worth 0 credits, then enter the number 0 in the field.");
break;
}
var validgrcheck = 0;
for (var xx = 0; xx < grcount; xx++)
{
if (ingr[x] == gr[xx])
{
allgr = allgr + (parseInt(incr[x],10) * cr[xx]);
allcr = allcr + parseInt(incr[x],10);
validgrcheck = 1;
break;
}
}
console.log(validgrcheck);
if (validgrcheck == 0)
{
alert("Error: Could not recognize the grade entered for subject " + eval(x + 1) + ". Please use standard college grades in the form of A+, A, B+ ... D-");
return 0;
}
}
if (allcr == 0)
{
alert("Error:You did not enter any credit values. GPA = N/A");
return 0;
}
gpa = allgr / allcr;
alert("GPA = " + gpa);
return 0;
}
<center>
<form name = "GPACalcForm">
<table border = "2" bgcolor = #bb8fce cellpadding = "5" cellspacing = "2">
<TH> </TH>
<TH>Grade</TH>
<TH>Credits</TH>
<TR>
<TD>IT 201</TD>
<TD><input type = "text" size = "5" name = "GR1" align = "top" maxlength = "5"></TD>
<TD><input type = "text" size = "5" name = "CR1" align = "top" maxlength = "5"></TD>
</TR>
<TR>
<TD>IT 202</TD>
<TD><input type = "text" size = "5" name = "GR2" align = "top" maxlength = "5"></TD>
<TD><input type = "text" size = "5" name = "CR2" align = "top" maxlength = "5"></TD>
</TR>
<TR>
<TD>IT 203</TD>
<TD><input type = "text" size = "5" name = "GR3" align = "top" maxlength = "5"></TD>
<TD><input type = "text" size = "5" name = "CR3" align = "top" maxlength = "5"></TD>
</TR>
<TR>
<TD>IT 204</TD>
<TD><input type = "text" size = "5" name = "GR4" align = "top" maxlength = "5"></TD>
<TD><input type = "text" size = "5" name = "CR4" align = "top" maxlength = "5"></TD>
</TR>
<TR>
<TD>IT 205</TD>
<TD><input type = "text" size = "5" name = "GR5" align = "top" maxlength = "5"></TD>
<TD><input type = "text" size = "5" name = "CR5" align = "top" maxlength = "5"></TD>
</TR>
<TR>
<TR align = "center">
<TD colspan = "3">
<input type = "button" value = "Calculate" name = "CalcButton" OnClick = "gpacalc()">
</TD>
</TR>
</table>
</form>
<br/>
<p> </p>
</center>
<br/>
I have made the following change in your code :-
if (ingr[x] == "")
break;
alert("Error: You did not enter a numeric credits value for subject. If the subject is worth 0 credits, then enter the number 0 in the field.");
to
if (ingr[x] == "") {
alert("Error: You did not enter a numeric credits value for subject. If the subject is worth 0 credits, then enter the number 0 in the field.");
break;
}

Javascript Range, Variance, and Standard Deviation Functions

So, I've been recently tasked to do a few calculations and to build a custom JS statistics library. The only 3 things I have left are to create functions for the range, variance, and standard deviation. What I'm doing here is passing my array (x) into the js functions, but they keep coming up blank. Am I doing something wrong?
function findSum(x)
{
var sum = 0;
for(i = 0; i < x.length; i++)
{
sum = sum + x[i];
}
return sum;
};
function findMean(x)
{
return findSum(x) / x.length;
};
function findMedian(x)
{
x.sort( function(a,b) {return a - b;} );
var half = Math.floor(x.length/2);
if(x.length % 2)
return x[half];
else
return (x[half-1] + x[half]) / 2.0;
}
// Ascending functions for sort
function ascNum(a, b) { return a - b; }
function clip(arg, min, max) {
return Math.max(min, Math.min(arg, max));
};
function findMode(x)
{
var arrLen = x.length;
var _arr = x.slice().sort(ascNum);
var count = 1;
var maxCount = 0;
var numMaxCount = 0;
var mode_arr = [];
var i;
for (i = 0; i < arrLen; i++) {
if (_arr[i] === _arr[i + 1]) {
count++;
} else {
if (count > maxCount) {
mode_arr = [_arr[i]];
maxCount = count;
numMaxCount = 0;
}
// are there multiple max counts
else if (count === maxCount) {
mode_arr.push(_arr[i]);
numMaxCount++;
}
// resetting count for new value in array
count = 1;
}
}
return numMaxCount === 0 ? mode_arr[0] : mode_arr;
};
function findRange(x)
{
x.sort( function (a, b) {return a-b;} );
}
function findVariance(x) {
var mean = findMean(x);
return findMean(array.map(findSum(sum)) {
return Math.pow(sum - mean, 2);
}));
},
function findStandardDeviation(x)
{
return Math.sqrt(findVariance(x));
};
The HTML code:
<html>
<head>
<h1>Statistical Calculations</h1>
<title>Calculating Stats</title>
<link rel="stylesheet" type="text/css" href="style.css">
<script src='Stats.js'></script>
<script language="JavaScript">
function addNumber()
{
var input = document.getElementById('input').value;
var list = document.getElementById('list');
var option = document.createElement('OPTION');
list.options.add(option);
option.text = input;
}
function getStatistics()
{
var list = new Array();
var select = document.getElementById('list');
for(i = 0; i < select.options.length; i++)
{
list[i] = parseInt(select.options[i].text);
}
document.getElementById('summation').value =findSum(list);
document.getElementById('mean').value = findMean(list);
document.getElementById('median').value = findMedian(list);
document.getElementById('mode').value = findMode(list);
document.getElementById('variance').value = findVariance(list);
document.getElementById('standardDev').value = findStandardDeviation(list);
document.getElementById('range').value = findRange(list);
document.getElementById('max').value = findMax(list);
document.getElementById('min').value = findMin(list);
}
</script>
</head>
<body>
<table>
<tr>
<td>Input Number:</td><td><input type='text' id='input'></td>
</tr>
<tr>
<td colpsan='2'><input type='button' value='Add Number' onClick='addNumber()'></td>
</tr>
<tr>
<td colspan='2'>
<select id='list' size='5'>
</select>
</td>
</tr>
<tr>
<td colpsan='2'><input type='button' value='Calculate!' onClick='getStatistics()'></td>
</tr>
<tr>
<td>Summation:</td><td><input type='text' id='summation' readonly></td>
</tr>
<tr>
<td>Mean:</td><td><input type='text' id='mean' readonly></td>
</tr>
<tr>
<td>Median:</td><td><input type='text' id='median' readonly> </td>
</tr>
<tr>
<td>Mode:</td><td><input type='text' id='mode' readonly></td>
</tr>
<tr>
<td>Max:</td><td><input type='text' id='max' readonly></td>
</tr>
<tr>
<td>Min:</td><td><input type='text' id='min' readonly></td>
</tr>
<tr>
<td>Range:</td><td><input type='text' id='range' readonly></td>
</tr>
<tr>
<td>Variance:</td><td><input type='text' id='variance' readonly></td>
</tr>
<tr>
<td>Standard Deviation:</td><td><input type='text' id='standardDev' readonly></td>
</tr>
</table>
</body>
</html>
The last 3 seem to do absolutely nothing, and I've been bashing my head in for the last few days trying to figure it out. If anyone could help sort my functions out into working order, it'd be greatly appreciated! I'm sure that the array has been passing into the functions correctly, seeing as the first 4 functions obviously worked.

What is wrong with my code?

I'm having trouble with my code but can't seem to find what the problem is. I keep getting the same errors in browser but I don't see what the problem is?
FVOM.js:16 Uncaught SyntaxError: Unexpected number
FVOM.html:15 Uncaught ReferenceError: CheckSelection is not defined
HTML code:
<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Future Value Demo</title>
<link rel="stylesheet" type="text/css" href="css/index.css"/>
<script type="text/javascript" src="JScripts/FVOM.js"></script>
</head>
<body>
<table>
<tr>
<td colspan="2">
<input type="radio" id="futVal" name="Money" checked onClick="FVOM:CheckSelection(1)"/>Future Value
<input type="radio" id="preVal" name="Money" onClick="FVOM:CheckSelection(2)"/>Present Value
<input type="radio" id="rate" name="Money" onClick="FVOM:CheckSelection(3)"/>Rate of Interest
<input type="radio" id="time" name="Money" onClick="FVOM:CheckSelection(4)"/>Years
</td>
</tr>
</table>
<br/>
<table>
<tr>
<td>Future Value (FV)</td>
<td><input type="text" id="FV" disabled/></td>
</tr>
<tr>
<td>Present Value (PV)</td>
<td><input type="text" id="PV" value = "1500" /></td>
</tr>
<tr>
<td>Interest Rate [pa] (r)</td>
<td><input type="text" id="R" value = "4.5"/></td>
</tr>
<tr>
<td>Years (n)</td>
<td><input type="text" id="N" value = "1"/></td>
</tr>
<tr>
<td>Compounded</td>
<td>
<select id="compounded">
<option value="year">Yearly</option>
<option value="quarter">Quarterly</option>
<option value="month">Monthly</option>
</select>
</td>
</tr>
<tr>
<td><input type="button" id="reset" value="RESET"/></td>
<td><input type="button" id="calculate" value="Calculate"/></td>
</tr>
</table>
<br/>
<hr/>
<br/>
<div id="results">
</div>
</body>
JavaScript:
var $ = function(id){
return document.getElementById(id);
};
var futureValue = function(){
var pv = parseFloat($("PV").value);
var r = parseFloat($("R").value);
var n = parseFloat($("N").value);
if(isNaN(pv) || isNaN(r) || isNaN(n)){
alert("Please enter a valid number");
}
else{
r = r/100/Compounded();
n = n*Compounded();
$("FV").value=(pv*Math.pow((1+r), n)).toFixed(2);
var res = "<table border="1"><tr><th>Period</th><th>Investment</th><th>Year End</th></tr>";
for(var i=1; i<=n; i++){
res+="<tr><td>"+i+"</td><td>€"+(pv).toFixed(2)+"</td><td>€"+(pv*Math.pow((1+r), 1)).toFixed(2)+"</td></tr>";
pv = pv*Math.pow((1+r), 1);
}
res+="</table>";
$("results").innerHTML = res;
}
};
var presentValue = function(){
var fv = parseFloat($("FV").value);
var r = parseFloat($("R").value);
var n = parseFloat($("N").value);
if(isNaN(fv) || isNaN(r) || isNaN(n))
alert("Please enter numbers");
else{
r = r/100/Compounded();
n = n*Compounded();
$("PV").value=(fv/Math.pow((1+r), n)).toFixed(2);
}
};
var rateOfInterest = function(){
var fv = parseFloat($("FV").value);
var pv = parseFloat($("PV").value);
var n = parseFloat($("N").value);
if(isNaN(fv) || isNaN(pv) || isNaN(n))
alert("Please enter numbers");
else{
n = n*Compounded();
$("R").value=((Math.pow((fv/pv),(1/n))-1)*100*Compounded()).toFixed(2)+"%";
}
};
var numberOfYears = function(){
var fv = parseFloat($("FV").value);
var pv = parseFloat($("PV").value);
var r = parseFloat($("R").value);
if(isNaN(fv) || isNaN(pv) || isNaN(r))
alert("Please enter numbers");
else{
r = r/100/Compounded;
$("N").value=(((Math.log(fv)-Math.log(pv))/Math.log(1 + r)))n/Compounded()).toFixed(2);
}
};
var Compounded = function(){
var com = $("compounded").value;
if(com=="year")
return 1;
if(com=="quarter")
return 4;
if(com=="month")
return 12;
};
var calculate = function(){
if($("futVal").checked)
futureValue();
if($("preVal").checked)
presentValue();
if($("rate").checked)
rateOfInterest();
if($("time").checked()
numberOfYears();
};
var CheckSelection = function(id){
if(id==1){
$("FV").disabled = true;
$("PV").disabled = false;
$("R").disabled = false;
$("N").disabled = false;
}
else if(id==2){
$("FV").disabled = false;
$("PV").disabled = true;
$("R").disabled = false;
$("N").disabled = false;
}
else if(id==3){
$("FV").disabled = false;
$("PV").disabled = false;
$("R").disabled = true;
$("N").disabled = false;
}
else{
$("FV").disabled = false;
$("PV").disabled = false;
$("R").disabled = false;
$("N").disabled = true;
}
RESET();
};
var RESET = function(){
$("FV").value = "";
$("PV").value = "";
$("R").value = "";
$("N").value = "";
$("results").innerHTML = "";
};
window.onload = function(){
$("calculate").onClick = calculate;
$("reset").onClick = RESET;
};
I'm fairly new to JavaScript so any help would be greatly appreciated.
var res = "<table border="1"><tr><th>Period</th><th>Investment</th><th>Year End</th></tr>";
is where the problem lies. You need to escape the " (double quotes) that exist in border="1" by either using a \" or by using single quotes '
For this reason some people use single quotes in javascript to assign a string, that way you do not need to escape the double quotes. If you would like to read more about strings in javascript there is a decent introduction at http://www.w3schools.com/js/js_strings.asp

Get Javascript calculator to do an equation like (5-3+2) with only 2 number inputs

I'm making this Javascript Calculator and I can't figure out how to get the calculator to do a problem like 5-(3+1), 5-3+1.
It only prints the 5-3 part of the equation not the +1
Here is my code:
<html>
<script>
function calc()
{
var D = "";
var A = document.getElementById("num1").value;
var B = document.getElementById("op").value;
var C = parseInt(document.getElementById("num2").value);
if(B == "+")
{
D = parseInt(A)+parseInt(C);
}
else if(B == "-")
{
D = parseInt(A)-parseInt(C);
}
else if(B == "*")
{
D = parseInt(A)*parseInt(C);
}
else if(B == "/")
{
D = parseInt(A)/parseInt(C);
}
else
{
alert("Error")
}
document.getElementById("result").value = parseInt(D);
}
function conteq()
{
var D = document.getElementById("result").value;
var E = "";
document.getElementById("num1").value = D;
document.getElementById("op").value = E;
document.getElementById("num2").value = E;
document.getElementById("result").value = E;
}
function resetcalc()
{
var E = "";
document.getElementById("num1").value = E;
document.getElementById("op").value = E;
document.getElementById("num2").value = E;
document.getElementById("result").value = E;
}
</script>
<body>
<table align="center">
<td>This is a basic Javascript Calculator.<br /></td></table>
<table align="center"><td>(Number 1)<input type="text" id="num1" align="middle" name="num1" />
</td>
<table align="center"><td>(Operator)<input type="text" align="middle" id="op" name="op" /></td> </table>
<table align="center"> <td>(Number 2)<input type="text" align="middle" id="num2" name="num2" /></td> </table>
<table align="center"> <td><input type="button" align="middle" value="=" onClick="calc()" /></td> </table>
<table align="center"><td>(Result)<input type="text" id="result" name="result" readonly />
</td></table>
<table align="center"><td><input type="button" value="Set Answer to Number 1" onClick="conteq()" /></td></table>
<table align="center"><td><input type="button" value="Reset" onClick="resetcalc()" /></td></table>
</table>
</p>
</body>
</html>
You're trying to convert ( to an integer, and you can't (because it isn't):
function calc()
{
var D = "";
var A = document.getElementById("num1").value;
var B = document.getElementById("op").value;
var C = document.getElementById("num2").value;
D = eval(A + B + C);
document.getElementById("result").value = D;
}

Categories