I have created this simple straight bet calculator using JavaScript.
It allows me to calculate, if it is a winning ticket, how much the payout will be.
How it works?
First I will enter the moneyLine number, which can be mostly any 3 digits number and I then enter the bet amount.
Now, the moneyLine can either be negative (-) if betting a favorite or positive (+) if betting the underdog.
Please see the code below:
For testing proposes, I use any -110 or 110 and then, any bet amount. But it can actually be any chosen moneyLine and betAmount.
// Single Straight Sports Bet Calculator
function betCalculator(moneyLine) {
var odds;
var betAmount = +prompt("Enter Bet Amount");
if (moneyLine >= 0) {
odds = moneyLine >= 0 ? (moneyLine / 100) + 1 : (100 / Math.abs(moneyLine)) + 1;
} else {
odds = moneyLine >= 0 ? (moneyLine / 100) + 1 : (100 / Math.abs(moneyLine)) + 1;
} return ((odds * betAmount).toFixed(2));
}
alert(betCalculator(+prompt("Enter Money Line")));
// Single Straight Sports Bet Calculator
function betCalculator(moneyLine) {
var odds;
var betAmount = +prompt("Enter Bet Amount");
if (moneyLine >= 0) {
odds = moneyLine >= 0 ? (moneyLine / 100) + 1 : (100 / Math.abs(moneyLine)) + 1;
} else {
odds = moneyLine >= 0 ? (moneyLine / 100) + 1 : (100 / Math.abs(moneyLine)) + 1;
} return ((odds * betAmount).toFixed(2));
}
alert(betCalculator(+prompt("Enter Money Line")));
And here is what I would like to have accomplished.
My desire is to create a Parlay Calculator, using the above formulas, that will allow me to enter one bet amount and several money lines, instead of just one.
A parlay is a single bet that links together two or more individual wagers for a high payout. So a parlay ticket can have two or more teams on it.
What I would also like to do is to be able to enter those numbers (moneyLine and betAmount) on a form instead of a popup window.
I tried doing it myself with no avail. Somehow, it is not showing the result.
// True Odds Parlay Bets
const myForm= document.getElementById("my-form")
var odds;
var moneyLine
, trueOdds=
{ 'moneyLine1 >= 0': (odds = moneyLine >= 0 ? (moneyLine / 100) + 1 : (100 / Math.abs(moneyLine)) + 1)
, 'moneyLine2 >= 0': (odds = moneyLine >= 0 ? (moneyLine / 100) + 1 : (100 / Math.abs(moneyLine)) + 1)
, 'moneyLine3 >= 0': (odds = moneyLine >= 0 ? (moneyLine / 100) + 1 : (100 / Math.abs(moneyLine)) + 1)
, 'moneyLine4 >= 0': (odds = moneyLine >= 0 ? (moneyLine / 100) + 1 : (100 / Math.abs(moneyLine)) + 1)
, 'moneyLine5 >= 0': (odds = moneyLine >= 0 ? (moneyLine / 100) + 1 : (100 / Math.abs(moneyLine)) + 1)
, 'moneyLine6 >= 0': (odds = moneyLine >= 0 ? (moneyLine / 100) + 1 : (100 / Math.abs(moneyLine)) + 1)
, 'moneyLine7 >= 0': (odds = moneyLine >= 0 ? (moneyLine / 100) + 1 : (100 / Math.abs(moneyLine)) + 1)
, 'moneyLine8 >= 0': (odds = moneyLine >= 0 ? (moneyLine / 100) + 1 : (100 / Math.abs(moneyLine)) + 1)
, 'moneyLine9 >= 0': (odds = moneyLine >= 0 ? (moneyLine / 100) + 1 : (100 / Math.abs(moneyLine)) + 1)
};
myForm.onsubmit = e=>e.preventDefault(); // disable form submit
myForm.oninput = betCalculator;
function betCalculator() {
let bet = myForm.betAmount.valueAsNumber, odds = trueOdds[(myForm.moneyLine1.value + '_' + myForm.moneyLine2.value + '_' + myForm.moneyLine3.value + '_' + myForm.moneyLine4.value + '_' + myForm.moneyLine5.value + '_' + myForm.moneyLine6.value + '_' + myForm.moneyLine7.value + '_' + myForm.moneyLine8.value + '_' + myForm.moneyLine9.value)];
// This code is used to get rid of "NaN"
if ( isNaN(bet) || isNaN(odds) ) {
return 0;
}
myForm.result.value = '" ' + '$ '+(odds * bet).toFixed(2) + ' "'
}
betCalculator()
fieldset { margin-top: 1em;}
label { display: inline-block; width: 6em; }
input[type="radio"] {
-webkit-appearance: checkbox; /* Chrome, Safari, Opera */
-moz-appearance: checkbox; /* Firefox */
-ms-appearance: checkbox;
}
<head>
<title>True Odds Parlay Bet Calculator</title>
<link rel="stylesheet" type="text/css" href="trueoddstyle.css">
</head>
<body>
<h2>True Odds Parlay Bet Calculator</h2>
<p>
Useful for both <b>Negative "-"</b> and/or <b>Positive "+"</b> Money Lines including Single Straight Bets!
</p>
<form action="" id="my-form">
<fieldset>
<legend>Bet Amount :</legend>
<input type="number" name="betAmount" step=any min=0>
</fieldset>
<fieldset>
<legend>Team Respective Money Line :</legend>
<input type="number" name="moneyLine1" step=any min=0>
<input type="number" name="moneyLine2" step=any min=0>
<input type="number" name="moneyLine3" step=any min=0>
<input type="number" name="moneyLine4" step=any min=0>
<input type="number" name="moneyLine5" step=any min=0>
<input type="number" name="moneyLine6" step=any min=0>
<input type="number" name="moneyLine7" step=any min=0>
<input type="number" name="moneyLine8" step=any min=0>
<input type="number" name="moneyLine9" step=any min=0>
</fieldset>
<fieldset>
<legend>Payout :</legend>
<output name="result" value=''></output>
<br><br>
<input type="reset" value="Reset Calculator!"</input>
</fieldset>
</form>
</body>
Please see the snippet code for details.
Your help is very appreciated.
Revised first version :)
const bt_Nwline = document.getElementById('New-Line')
, xForm = document.getElementById('form-X')
, wTable = xForm.querySelector('table')
, baseLine = wTable.querySelector('thead tr:nth-of-type(3)')
, tBody = wTable.querySelector('tbody')
, tPayout = wTable.querySelector('tfoot td:nth-of-type(2)')
;
xForm.onsubmit = e=>e.preventDefault() // disable form submit
;
xForm.onreset =_=>{ tPayout.textContent = '0.00' }
;
function betCalculator()
{
let bet = xForm.betAmount.valueAsNumber || 0
, odds = [...tBody.querySelectorAll('input')]
.filter(ml=>!isNaN(ml.valueAsNumber) )
.reduce((odd,ml)=> odd *= ml.valueAsNumber >= 0
? (ml.valueAsNumber /100) +1
: (100 / Math.abs(ml.valueAsNumber)) +1
,1)
tPayout.textContent = ((odds *bet).toFixed(2)).replace(/\B(?=(\d{3})+(?!\d))/g,',')
}
betCalculator()
;
bt_Nwline.onclick=_=>
{
tBody.appendChild( baseLine.cloneNode(true))
}
tBody.onclick=e=>
{
if (!e.target.matches('button')) return
wTable.deleteRow(e.target.closest('tr').rowIndex)
betCalculator()
}
xForm.oninput = betCalculator
;
table { border-collapse: collapse; }
caption { background-color: #1a4641; color: whitesmoke; font-weight: bold; padding: .6em;}
td:nth-of-type(1) { min-width:8em; }
td { border: 1px solid grey; padding: .4em .8em; }
thead { background-color: #7adfd3; color: #1d1313; font-weight: bold; }
thead tr:nth-of-type(1) td:nth-of-type(1) { text-align: right; }
thead tr:nth-of-type(2) td:nth-of-type(1) { text-align: center; }
thead tr:nth-of-type(3) { display: none; counter-reset: line; }
tbody tr { counter-increment: line; }
tbody td:nth-of-type(1) { color: darkslategrey; }
tbody td:nth-of-type(1)::before { content: counter(line) '\00a0-\00a0\00a0'; }
tfoot { font-weight: bold; }
tfoot td:nth-of-type(1) { text-align: right; }
tfoot td:nth-of-type(2)::before { content: '$ ' }
input { font-size: 1.2em; text-align: right; direction: rtl; width:8em;}
button {
width: 2em;
height: 1.4em;
border-radius: 1em / .6em;
color: whitesmoke;
font-size: .9em;
font-weight: bolder;
line-height: .8em;
padding: 0;
}
thead tr:nth-of-type(1) button { background-color: #063329; }
thead tr:nth-of-type(2) button { background-color: crimson; }
tbody button { background-color: #071b3f;}
<form action="" id="form-X">
<table>
<caption title="Useful for both Negative ‘−’ and / or Positive ‘+’ Money Lines including Single Straight Bets!">
True Odds Parlay Bet Calculator
</caption>
<thead>
<tr>
<td>Bet Amount : </td>
<td><input type="number" step="10" value="0" name="betAmount" min="0"></td>
<td><button type="reset">∅</button></td>
</tr>
<tr><td colspan="2">Teams Money Lines</td> <td><button id="New-Line">+</button></td></tr>
<tr>
<td contenteditable spellcheck="false">...</td>
<td><input type="number" step="10" value="0"></td>
<td><button>−</button></td>
</tr>
</thead>
<tbody>
</tbody>
<tfoot>
<tr>
<td> Payout : </td>
<td colspan="2"> </td>
</tr>
</tfoot>
</table>
</form>
After looking your second Snippet I do that:
const myForm = document.getElementById('my-form')
, moneyLines = [...myForm.querySelectorAll('.moneyLine')]
;
myForm.onsubmit = e=>e.preventDefault() // disable form submit
;
myForm.oninput = betCalculator
;
function betCalculator()
{
let bet = myForm.betAmount.valueAsNumber || 0
, odds = moneyLines
.filter(ml=>!isNaN(ml.valueAsNumber) )
.reduce((odd,ml)=> odd *= ml.valueAsNumber >= 0
? (ml.valueAsNumber /100) +1
: (100 / Math.abs(ml.valueAsNumber)) +1
,1)
myForm.result.value = (odds *bet).toFixed(2)
}
betCalculator()
form#my-form { position: relative; }
legend {font-size: .9em; }
legend:after { content: '\00a0' }
fieldset { display:block; width: 16em; position: absolute; }
fieldset:nth-child(1){ top: 1em; left: 1em; }
fieldset:nth-child(2){ top: 1em; left:20em; }
fieldset:nth-child(3){ top:19em; left: 1em; }
label { display: block; float: left; clear: both; margin: .2em 1em .4em 0;}
label b { display: inline-block; width:2em }
label b::after { content:' : '}
label input { font-size: 1.2em; text-align: right; direction: rtl; width:8em;}
output { font-weight: bold; width: 14em; border-bottom: 1px solid lightgrey; display: block; margin: .8em; float: right; text-align: right;}
output::before { content: '$ '; }
<h2>True Odds Parlay Bet Calculator</h2>
<p><small>
Useful for both <b>Negative "−"</b> and/or <b>Positive "+"</b> Money Lines including Single Straight Bets!
</small></p>
<form action="" id="my-form">
<fieldset>
<legend>Bet Amount :</legend>
<label><input type="number" name="betAmount" step=any min=0></label>
</fieldset>
<fieldset>
<legend>Team Respective Money Lines :</legend>
<label><b>1</b><input type="number" class="moneyLine" step=any ></label>
<label><b>2</b><input type="number" class="moneyLine" step=any ></label>
<label><b>3</b><input type="number" class="moneyLine" step=any ></label>
<label><b>4</b><input type="number" class="moneyLine" step=any ></label>
<label><b>5</b><input type="number" class="moneyLine" step=any ></label>
<label><b>6</b><input type="number" class="moneyLine" step=any ></label>
<label><b>7</b><input type="number" class="moneyLine" step=any ></label>
<label><b>8</b><input type="number" class="moneyLine" step=any ></label>
<label><b>9</b><input type="number" class="moneyLine" step=any ></label>
</fieldset>
<fieldset>
<legend>Payout :</legend>
<output name="result" value='0'></output>
<br><br>
<button type="reset">Reset Calculator!</button>
</fieldset>
</form>
Related
I am trying to create a custom error message when a number which is too high or low is entered in the "size" element. However, I am unable to make this work. I am a beginner so a solution which involves the least changes to my existing code would be most appreciated.
function autoFillcost() {
var size = document.getElementById("size").value;
if (size <= 25)
document.getElementById("cost").value = "£100";
else if (size >= 26 && size <= 50)
document.getElementById("cost").value = "£200";
else
document.getElementById("cost").value = "£300";
}
function sizeValidate() {
var size = document.getElementById("size");
if (!size.checkValidity()) {
size.setCustomValidity("ERROR!");
} else {
size.setCustomValidity("");
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<body>
<form>
Group Size:<input type="number" min="6" max="200" id="size" onblur="autoFillcost();sizeValidate();" required>
<p>Cost:<input type="text" id="cost"></p>
<p id="demo"></p>
</form>
</body>
</html>
Sorry for digging, but it is possible, just report it after you set it.
Hopefully this helps others.
if (!size.checkValidity()) {
size.setCustomValidity("ERROR!");
size.reportValidity();
}
The problem with setCustomValidity is, that it does only work once you submit the form.
function autoFillcost() {
var size = document.getElementById("size").value;
if (size <= 25)
document.getElementById("cost").value = "£100";
else if (size >= 26 && size <= 50)
document.getElementById("cost").value = "£200";
else
document.getElementById("cost").value = "£300";
}
function sizeValidate() {
var size = document.getElementById("size");
if (!size.checkValidity()) {
size.setCustomValidity("ERROR!");
} else {
size.setCustomValidity("");
}
}
button {
padding:6px;
cursor:pointer;
}
input {
padding:5px;
border:1px solid #aaa;
box-shadow: 0px 0px 3px #ccc, 0 10px 15px #eee inset;
border-radius:2px;
}
input:valid {
background-color: white;
}
input:invalid {
background-color: lightpink;
}
<form>
Group Size:<input type="number" min="6" max="200" id="size" onblur="autoFillcost();sizeValidate();" required />
<p>Cost:<input type="text" id="cost"></p>
<p id="demo"></p>
<button type="submit">Submit</button>
</form>
in my class we are using firstChild.nodeValue to display text if a user enters in an incorrect value. However, I can't get my two other fields to display the error message and only the first one. What am I doing wrong? When I run it in the code snipped is says that the nodeValue is null. I have the error messages display through a span and they are being used by the firstChild.nodeValue.
var $ = function (id) {
return document.getElementById(id);
}
var calculateClick = function () {
var investment = parseInt( $("investment").value);
var rate = parseFloat( $("rate").value);
var years = parseInt($("years").value);
//var amount = interest * rate * years;
if (investment==="" || investment < 100 || investment > 100000){
$("investment_error").firstChild.nodeValue="Must be an integer from 100 - 100,000";
}
else if (rate ==="" || rate <0.1 || rate >12){
$("rate_error").firstChild.nodeValue="Must be a value from .1 - 12";
}
else if (years ==="" || years <1 || years > 50){
$("years_error").firstChild.nodeValue="Must be an integer from 1 - 50";
}
var nt = 4*years;
var amount = investment * (1 + (rate/4)) ** nt;
$("future_value").value=amount.toFixed(2);
}
var clear_fields = function (){
$("investment").value="";
$("rate").value="";
$("years").value="";
$("future_value").value="";
}
window.onload = function () {
$("calculate").onclick = calculateClick;
$("calculate").ondblclick=clear_fields;
$("investment").focus();
}
body {
font-family: Arial, Helvetica, sans-serif;
background-color: white;
margin: 0 auto;
width: 48%;
padding: 0 1em .5em;
border: 3px solid blue;
}
h1 {
margin: .5em 0;
text-align: center;
}
label {
float: left;
width: 10em;
text-align: right;
padding-bottom: .5em;
}
input {
margin-left: 1em;
margin-bottom: .5em;
}
span {
color: blue;
}
<!DOCTYPE html>
<html>
<head>
<title>Future Value Calculator</title>
<link rel="stylesheet" href="future_value.css">
<script src="future_value.js"></script>
</head>
<body>
<main>
<h1 id="heading">Future Value Calculator</h1>
<label for="investment">Investment Amount:</label>
<input type="text" id="investment">
<span id="investment_error"> </span><br>
<label for="rate">Annual Interest Rate:</label>
<input type="text" id="rate">
<span id="rate_error"></span><br>
<label for="years">Number of Years:</label>
<input type="text" id="years">
<span id="years_error"></span><br>
<label for="future_value">Future Value:</label>
<input type="text" id="future_value" disabled="disabled"><br>
<label> </label>
<input type="button" id="calculate" value="Calculate"><br>
</main>
</body>
</html>
Its working on the first span becouse you have space between the span tags as:
with space
<span id="investment_error"> </span>
without
<span id="rate_error"></span>
In any case you should use innerHTML instead.
first child is good in case you already have a child in the html tags like this
<div>
<p id="i_am_div_first_child"> first child</p>
</div>
please hit correct answer if that was helpfull.
So what is the difference? A simple test will show you why.
console.log("1:", document.querySelector("#s1").firstChild)
console.log("2:", document.querySelector("#s2").firstChild)
<span id="s1"> </span>
<span id="s2"></span>
The one has a whitespace in it, the others do not the one with the whitespace has a firstChild, the others do not.
What should you do?
I would just set the textContent or innerHTML of the span and not set the nodeValue.
And another issue with your code, is you have
var rate = parseFloat( $("rate").value);
and
if ( rate==="")
That empty string check is not going to happen to be true ever since parseFloat is going to return NaN.
$("rate_error").firstChild returns null because it has no childrne (not even whit space), and so does not have a nodeValue property.
You could just use innerHTML instead of firstChild.nodeValue.
Also you don't need the else, just tell the user immediately all they have to fix.
var $ = function(id) {
return document.getElementById(id);
}
var calculateClick = function() {
var investment = parseInt($("investment").value);
var rate = parseFloat($("rate").value);
var years = parseInt($("years").value);
//var amount = interest * rate * years;
if (investment === "" || investment < 100 || investment > 100000) {
$("investment_error").innerHTML = "Must be an integer from 100 - 100,000";
}
if (rate === "" || rate < 0.1 || rate > 12) {
$("rate_error").innerHTML = "Must be a value from .1 - 12";
}
if (years === "" || years < 1 || years > 50) {
$("years_error").innerHTML = "Must be an integer from 1 - 50";
}
var nt = 4 * years;
var amount = investment * (1 + (rate / 4)) ** nt;
$("future_value").value = amount.toFixed(2);
}
var clear_fields = function() {
$("investment").value = "";
$("rate").value = "";
$("years").value = "";
$("future_value").value = "";
}
window.onload = function() {
$("calculate").onclick = calculateClick;
$("calculate").ondblclick = clear_fields;
$("investment").focus();
}
body {
font-family: Arial, Helvetica, sans-serif;
background-color: white;
margin: 0 auto;
width: 48 %;
padding: 0 1em .5em;
border: 3px solid blue;
}
h1 {
margin: .5em 0;
text-align: center;
}
label {
float: left;
width: 10em;
text-align: right;
padding-bottom: .5em;
}
input {
margin-left: 1em;
margin-bottom: .5em;
}
span {
color: blue;
}
<!DOCTYPE html>
<html>
<head>
<title>Future Value Calculator</title>
<link rel="stylesheet" href="future_value.css">
<script src="future_value.js"></script>
</head>
<body>
<main>
<h1 id="heading">Future Value Calculator</h1>
<label for="investment">Investment Amount:</label>
<input type="text" id="investment">
<span id="investment_error"> </span><br>
<label for="rate">Annual Interest Rate:</label>
<input type="text" id="rate">
<span id="rate_error"></span><br>
<label for="years">Number of Years:</label>
<input type="text" id="years">
<span id="years_error"></span><br>
<label for="future_value">Future Value:</label>
<input type="text" id="future_value" disabled="disabled"><br>
<label> </label>
<input type="button" id="calculate" value="Calculate"><br>
</main>
</body>
</html>
I have a form that calculates price per square meters of ceiling.
And ion range slider as input, then it calculates price and outputs data to inputs. But I need to change inputs with span or div. Any suggestions?
Here is the html:
<form id="calc">
<div id="1">
<p>
<input id="rel" oninput="
var v = this.value;
this.form.new.value = isNaN(v) ? '' : (v * 450).toFixed (0);
var v = this.value; this.form.new2.value = isNaN(v) ? '' : (v * 650).toFixed (0)"
style="display: none;">
</p>
<p><p>
<span class="small">from </span>
<span class="new"></span>
<input type="text" disabled="disabled" name="new" size="2" maxlength="4" value="0" >
<span class="small">to </span><input type="text" disabled="disabled" name="new2" size="2" maxlength="4" value="0">
<div class="result" id="result">
</div>
</p>
</div>
</form>
and here you can find how it works http://jsfiddle.net/khvoroffski/50apyyr5/
Please make a good look at this example , I made you func you make design (css) .
/*Chrome*/
#media screen and (-webkit-min-device-pixel-ratio:0) {
input[type='range'] {
overflow: hidden;
width: 10px;
-webkit-appearance: none;
background-color: #9a905d;
}
input[type='range']::-webkit-slider-runnable-track {
height: 10px;
-webkit-appearance: none;
color: #13bba4;
margin-top: -1px;
}
input[type='range']::-webkit-slider-thumb {
width: 10px;
-webkit-appearance: none;
height: 10px;
cursor: ew-resize;
background: #434343;
box-shadow: -10px 0 0 0px #43e5f7;
}
}
/** FF*/
input[type="range"]::-moz-range-progress {
background-color: #43e5f7;
}
input[type="range"]::-moz-range-track {
background-color: #9a905d;
}
/* IE*/
input[type="range"]::-ms-fill-lower {
background-color: #43e5f7;
}
input[type="range"]::-ms-fill-upper {
background-color: #9a905d;
}
<script>
function E (ele) {return document.getElementById(ele)}
function CALC ( value_ ) {
var SPAN = E("SliderValue")
var FROM = E("FROM")
var TO = E("TO")
var currentValue = E("SliderValue")
var WIDTH_OF_SLIDER = E("rel")
var positionInfo = WIDTH_OF_SLIDER.getBoundingClientRect();
var width_IN_PIX = positionInfo.width;
FROM.value = isNaN(value_) ? '' : (value_ * 450).toFixed (0);
TO.value = isNaN(value_) ? '' : (value_ * 650).toFixed (0);
currentValue.innerHTML = value_ + ""
var COEFICIJENT = width_IN_PIX / 100
currentValue.style.left = ( value_ * COEFICIJENT ) + "px"
}
</script>
<form id="calc"
>
<div id="1">
<p>
<input id="rel"
oninput="CALC(this.value)"
type="range"
maxValue="50"
minValue="5"
value="0"
step="1"
style="width:100%;background-color:red;" >
</p>
<span class="small" >from </span>
<span id="SliderValue" style="position:absolute;left:0;" > </span>
<input type="text" id="FROM" value="0" />
<span class="small">to </span>
<input type="text" id="TO" value="0" />
<div class="result" id="result" > </div>
</div>
</form>
I apologize for asking silly questions, but I have tried to mess with the CSS and changed very little. I am trying to get the label/dropdown (which says "withdrawal" by default to align with the others and also get rid of some of the space between the text areas so that it looks more like the screenshot provided by my instructor. I did manage to reduce some of the extra space between areas by reducing the pixels, but I am not certain how to get it to look exactly like the screenshot.
If anyone would please give suggestions, I would genuinely appreciate it.
var pad_left = function(text, width, pad) { //sets up text area formatting
var result = text.toString();
while (result.length < width) {
result = pad + result;
}
return result; // populates text area
}
var pad_right = function(text, width, pad) { // sets up text area formatting
var result = text.toString();
while (result.length < width) {
result = result + pad;
}
return result;
}
var getResults = function(results) { // actual calculation functions
if (results.length == 0) {
return "";
}
var balance = 2000; / /actual format of text area
var list = pad_right("Date", 12, " ");
list += pad_right("Amount", 12, " ");
list += pad_right("Running Balance", 15, " ") + "\n";
list += pad_right("", 11, "-") + " ";
list += pad_right("", 11, "-") + " ";
list += pad_right("", 15, "-") + "\n";
for (var i = 0; i < results.length; i++) { // loop to calculate balances
var trans = results[i];
list += pad_right(trans["date"], 12, " ");
if(trans["type"] == "withdrawal") // withdrawal calculation
{
balance -= trans["amount"]
list += "$" + pad_left( "-" + trans["amount"].toFixed(2), 11, " ") + " ";
} else { //for Deposits
balance += trans["amount"]
list += "$" + pad_left( trans["amount"].toFixed(2), 11, " ") + " ";
}
list += "$" + pad_left(balance.toFixed(2), 14, " ") + "\n";
}
return list;
}
var get_runningBalance = function(results) { // function to calculate Running Balance
var runningBalance = 0, amount;
for (var i in results) {
runningBalance = startBal - "amount" ;
runningBalance += parseInt(runningBalance.toFixed(2));
}
return runningBalance;
}
var get_startBal = function(transactions){ // fills Starting Balance
return 2000;
}
var get_totalDep = function(transactions){ // function to calculate Total Deposits
var totalDep = 0;
for(var i = 0; i < transactions.length; i++){
var trans = transactions[i];
if(trans["type"] == "deposit")
{
totalDep += trans["amount"]
}
}
return totalDep;
}
var get_totalWd = function(transactions){ // function to calculate Total Withdrawals
var totalWd = 0;
for(var i = 0; i < transactions.length; i++){
var trans = transactions[i];
if(trans["type"] == "withdrawal")
{
totalWd -= trans["amount"]
}
}
return totalWd;
}
var get_endBal = function(transactions){ // function to calculate Ending Balance
var balance = 2000;
for(var i = 0; i < transactions.length; i++){
var trans = transactions[i];
if(trans["type"] == "withdrawal")
{
balance -= trans["amount"]
} else { // Is Deposit
balance += trans["amount"]
}
}
return balance.toFixed(2);
}
// sets up the global variables and arrays for the functions
var balances = [];
var transactions = [];
var $ = function (id) {
return document.getElementById(id);
}
// pulls the info from text boxes
var update_display = function() {
$("startBal").value = get_startBal(transactions);
$("totalDep").value = get_totalDep(transactions);
$("totalWd").value = get_totalWd(transactions);
$("endBal").value = get_endBal(transactions);
$("date").value = "";
$("amount").value = "";
$("date").focus();
$("results").value = getResults(transactions);
}
// function to add transactions to the text area
var addTrans_click = function () {
var trans = [];
trans["date"] = $("date").value;
trans["amount"] = parseFloat($("amount").value);
trans["type"] = $("type").value;
if (trans["date"] == "") return;
if (isNaN(trans["amount"])) return;
transactions.push(trans);
update_display();
}
// the event handlers
window.onload = function () {
$("addTrans").onclick = addTrans_click;
$("date").focus();
}
body {
background: none repeat scroll;
font-family: Arial,Helvetica,sans-serif;
}
#content {
background: none repeat scroll;
border: 8px solid gray;
margin: 10px auto;
padding: 5px 20px;
text-align: center;
width: 600px;
}
h1, h2 {
text-align: left;
}
label {
display: block;
float: left;
padding-right: 1em;
text-align: right;
width: 10em;
}
input {
display: block;
float: left;
}
select {
display: block;
text-align: center;
width: 10em;
}
.formLayout label {
float: left;
text-align: right;
width: 10em;
}
.formLayout input {
margin-bottom: 0.5em;
margin-left: 0.5em;
}
.formLayout br {
clear: both;
}
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Monthly Balance Calculator</title>
<link href="monthly_balance.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="mbc_library.js"></script>
<script type="text/javascript" src="monthly_balance.js"></script>
</head>
<body>
<div id="content">
<h1>Monthly Balance Calculator</h1>
<br />
<h2>Add Transaction</h2>
<hr />
<br />
<div class="formLayout">
<label for="date">Date:</label>
<input type="text" name="date" id="date" />
<br />
<br />
<label for="type">Type:</label>
<select name="type" id="type">
<option value="withdrawal">Withdrawal</option>
<option value="deposit">Deposit</option>
</select>
<br />
<label for="amount">Amount:</label>
<input type="text" name="amount" id="amount"/>
<br />
<br />
<label> </label>
<input type="button" id="addTrans" value="Add Transaction" />
<br />
</div>
<h2>Transactions</h2>
<hr />
<br />
<textarea name="results" id="results" rows="10" cols="60" disabled="disabled">
</textarea>
<br />
<br />
<h2>Summary</h2>
<hr />
<br />
<div class="formLayout">
<label for="startBal">Starting Balance:</label>
<input type="text" name="startBal" id="startBal"
class="disabled" disabled="disabled"/>
<br />
<br />
<label for="totalDep">Total Deposits:</label>
<input type="text" name="totalDep" id="totalDep"
class="disabled" disabled="disabled"/>
<br />
<br />
<label for="totalWd">Total Withdrawals:</label>
<input type="text" name="totalWd" id="totalWd"
class="disabled" disabled="disabled"/>
<br />
<br />
<label for="endBal">Ending Balance</label>
<input type="text" name="endBal" id="endBal"
class="disabled" disabled="disabled"/>
<br />
<br />
</div>
</body>
</html>
Note, I had to add BOTH JS files in the same form because this site only allows me to paste two, despite the fact that I added two to the HTML page
I think this is what you need.
Check with below code.
var pad_left = function(text, width, pad) { //sets up text area formatting
var result = text.toString();
while (result.length < width) {
result = pad + result;
}
return result; // populates text area
}
var pad_right = function(text, width, pad) { // sets up text area formatting
var result = text.toString();
while (result.length < width) {
result = result + pad;
}
return result;
}
var getResults = function(results) { // actual calculation functions
if (results.length == 0) {
return "";
}
var balance = 2000; / /actual format of text area
var list = pad_right("Date", 12, " ");
list += pad_right("Amount", 12, " ");
list += pad_right("Running Balance", 15, " ") + "\n";
list += pad_right("", 11, "-") + " ";
list += pad_right("", 11, "-") + " ";
list += pad_right("", 15, "-") + "\n";
for (var i = 0; i < results.length; i++) { // loop to calculate balances
var trans = results[i];
list += pad_right(trans["date"], 12, " ");
if(trans["type"] == "withdrawal") // withdrawal calculation
{
balance -= trans["amount"]
list += "$" + pad_left( "-" + trans["amount"].toFixed(2), 11, " ") + " ";
} else { //for Deposits
balance += trans["amount"]
list += "$" + pad_left( trans["amount"].toFixed(2), 11, " ") + " ";
}
list += "$" + pad_left(balance.toFixed(2), 14, " ") + "\n";
}
return list;
}
var get_runningBalance = function(results) { // function to calculate Running Balance
var runningBalance = 0, amount;
for (var i in results) {
runningBalance = startBal - "amount" ;
runningBalance += parseInt(runningBalance.toFixed(2));
}
return runningBalance;
}
var get_startBal = function(transactions){ // fills Starting Balance
return 2000;
}
var get_totalDep = function(transactions){ // function to calculate Total Deposits
var totalDep = 0;
for(var i = 0; i < transactions.length; i++){
var trans = transactions[i];
if(trans["type"] == "deposit")
{
totalDep += trans["amount"]
}
}
return totalDep;
}
var get_totalWd = function(transactions){ // function to calculate Total Withdrawals
var totalWd = 0;
for(var i = 0; i < transactions.length; i++){
var trans = transactions[i];
if(trans["type"] == "withdrawal")
{
totalWd -= trans["amount"]
}
}
return totalWd;
}
var get_endBal = function(transactions){ // function to calculate Ending Balance
var balance = 2000;
for(var i = 0; i < transactions.length; i++){
var trans = transactions[i];
if(trans["type"] == "withdrawal")
{
balance -= trans["amount"]
} else { // Is Deposit
balance += trans["amount"]
}
}
return balance.toFixed(2);
}
// sets up the global variables and arrays for the functions
var balances = [];
var transactions = [];
var $ = function (id) {
return document.getElementById(id);
}
// pulls the info from text boxes
var update_display = function() {
$("startBal").value = get_startBal(transactions);
$("totalDep").value = get_totalDep(transactions);
$("totalWd").value = get_totalWd(transactions);
$("endBal").value = get_endBal(transactions);
$("date").value = "";
$("amount").value = "";
$("date").focus();
$("results").value = getResults(transactions);
}
// function to add transactions to the text area
var addTrans_click = function () {
var trans = [];
trans["date"] = $("date").value;
trans["amount"] = parseFloat($("amount").value);
trans["type"] = $("type").value;
if (trans["date"] == "") return;
if (isNaN(trans["amount"])) return;
transactions.push(trans);
update_display();
}
// the event handlers
window.onload = function () {
$("addTrans").onclick = addTrans_click;
$("date").focus();
}
body {
background: none repeat scroll 0 0 rgba(0, 0, 0, 0);
font-family: Arial,Helvetica,sans-serif;
}
#content {
background: none repeat scroll 0 0 rgba(0, 0, 0, 0);
border: 8px solid gray;
margin: 10px auto;
padding: 5px 20px;
text-align: center;
width: 600px;
}
h1, h2 {
text-align: left;
}
h2 {
margin-bottom: 0;
padding-bottom: 0;
}
label {
display: block;
float: left;
text-align: right;
width: 10em;
}
input {
display: block;
float: left;
}
select {
display: block;
float: left;
text-align: center;
width: 10em;
margin-bottom: 0.5em;
margin-left: 0.5em;
}
.formLayout label {
float: left;
text-align: right;
width: 10em;
}
.formLayout input {
margin-bottom: 0.5em;
margin-left: 0.5em;
}
.formLayout br {
clear: both;
}
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Monthly Balance Calculator</title>
<link href="monthly_balance.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="mbc_library.js"></script>
<script type="text/javascript" src="monthly_balance.js"></script>
</head>
<body>
<div id="content">
<h1>Monthly Balance Calculator</h1>
<br />
<h2>Add Transaction</h2>
<hr />
<br />
<div class="formLayout">
<label for="date">Date:</label>
<input type="text" name="date" id="date" />
<br />
<label for="type">Type:</label>
<select name="type" id="type">
<option value="withdrawal">Withdrawal</option>
<option value="deposit">Deposit</option>
</select>
<br />
<label for="amount">Amount:</label>
<input type="text" name="amount" id="amount"/>
<br />
<label> </label>
<input type="button" id="addTrans" value="Add Transaction" />
<br />
</div>
<h2>Transactions</h2>
<hr />
<br />
<textarea name="results" id="results" rows="10" cols="60" disabled="disabled">
</textarea>
<br />
<br />
<h2>Summary</h2>
<hr />
<br />
<div class="formLayout">
<label for="startBal">Starting Balance:</label>
<input type="text" name="startBal" id="startBal"
class="disabled" disabled="disabled"/>
<br />
<label for="totalDep">Total Deposits:</label>
<input type="text" name="totalDep" id="totalDep"
class="disabled" disabled="disabled"/>
<br />
<label for="totalWd">Total Withdrawals:</label>
<input type="text" name="totalWd" id="totalWd"
class="disabled" disabled="disabled"/>
<br />
<label for="endBal">Ending Balance</label>
<input type="text" name="endBal" id="endBal"
class="disabled" disabled="disabled"/>
<br />
</div>
</body>
</html>
I don't have much experience with HTML or javascript coding and I am trying to make a simple calculation app. This is what I have so far:
<!DOCTYPE html>
<html>
<head>
<style>
#p1 {
float:left;
padding:5px 150px;
}
#h1 {
float:left;
padding:5px 150px;
}
#v1 {
float:left;
padding:5px 150px;
}
#p2 {
padding:5px 150px;
}
#h2 {
padding:5px 150px;
}
#v2 {
padding:5px 150px;
}
</style>
</head>
<body>
<h1><center><b>Bernoulli's Energy Balance</b></center></h1>
<center><h2>P<sub>1</sub> + ρ*g*h<sub>1</sub> + ρ*(<sup>V<sub>1</sub><sup>2</sup></sup>⁄<sub>2</sub>) = P<sub>2</sub> + ρ*g*h<sub>2</sub> + ρ*(<sup>V<sub>2</sub><sup>2</sup></sup>⁄<sub>2</sub>) + ρ*F</h2></center>
<form name="boxes" action="">
<div id="p1" name="p1">
P<sub>1</sub>:<input type="text" name="P1" size=3></div>
<div id="p2" name="p2" align="right">
P<sub>2</sub>:<input type="text" name="P2" size=3><br></div><br>
<div id="h1" name="h1">
h<sub>1</sub>:<input type-"text" name="h1" size=3></div>
<div id="h2" name="h2" align="right">
h<sub>2</sub>:<input type-"text" name="h2" size=3></div><br>
<div id="v1" name="v1">
V<sub>1</sub>:<input type-"text" name="V1" size=3></div>
<div id="v2" name="v2" align="right">
V<sub>2</sub>:<input type-"text" name="V2" size=3></div><br>
<div id="rho" name="rho" align="center">
ρ:<input type="text" name="rho" size=3></div><br>
<div id="F" name="F" align="center">
F:<input type="text" name="F" size=3></div><br>
<div id="g" name="g" align="center">
g:<input type="text" name="g" size=3 value="9.8"></div><br>
<input type="button" onclick="calculate();" value="Calculate">
</form>
<script type="text/javascript" language="javascript" charset="utf-8">
function isEmpty(id) {
var text = document,getElementById(id).value;
if (!text.match(/\S/)){
return true;
}
else{
return false;
}
}
function calculate(){
var p1 = parseInt(document.getElementById("p1").value);
var p2 = parseInt(document.getElementById("p2").value);
var h1 = parseInt(document.getElementById("h1").value);
var h2 = parseInt(document.getElementById("h2").vaule);
var v1 = parseInt(document.getElementById("v1").value);
var v2 = parseInt(document.getElementById("v2").value);
var rho = parseInt(document.getElementById("rho").value);
var F = parseInt(document.getElementById("F").value);
var g = parseInt(document.getElementById("g").value);
var Lside = p1+(rho*g*h1)+(rho*((v1^2)/2));
var Rside = p2+(rho*g*h2)+(rho*((v2^2)/2))+(rho*F);
var ans = 0;
if (isEmpty(p1)){
ans = Rside-(rho*((v1^2)/2))-(rho*g*h1);
document.getElementById("p1").value = ans.toString();
}
else if (isEmpty(h1)){
ans = (Rside-(rho*((v1^2)/2))-p1)/(rho*g);
document.getElementById("h1").value = ans.toString();
}
else if (isEmpty(v1)){
ans = (Rside-p1-(rho*g*h1))/rho;
ans = ans*2;
ans = Math.sqrt(ans);
document.getElementById("v1").value = ans.toString();
}
else if (isEmpty(p2)){
ans = Lside-(rho*((v2^2)/2))-(rho*g*h2)-(rho*F);
document.getElementById("p2").value = ans.toString();
}
else if (isEmpty(h2)){
ans = (Lside-(rho*((v2^2)/2))-(rho*F)-p2)/(rho*g);
document.getElementById("h2").value = ans.toString();
}
}
</script>
</body>
</html>
I am trying to do the calculations and have the answer displayed in a text box. If that cannot be done I have also tried to display the answer in a tag but that did not work either.
Here is what the code looks like so far: http://jsfiddle.net/fCXMt/238/
It is supposed to find which text field is left blank and then do the calculation to find the value by using the other values which will all be given.
Quickly went through your code, the id's assigned are assigned to the div's and not the input values themselves.You are getting the wrong id's as from what i can see.
var p1 = parseInt(document.getElementById("p1").value);
should be
var p1 = parseInt(document.getElementById("P1").value);//notice the capital.
I also see that some divs that contain the input have id's but not the input fields themselves.
On line 76 you have a typo
var text = document,getElementById(id).value;
it should be document.getElementById(id).value;
Your code is full of errors. This is what it looks like after correcting the errors.
Demo on Fiddle
(For some reason, the first six inputs are unclickable on the fiddle. So, to get the focus on those inputs, click on the left top corner of the Result window and press the Tab key.)
HTML:
<div class="container">
<h1><center><b>Bernoulli's Energy Balance</b></center></h1>
<center>
<h2>P<sub>1</sub> + ρ*g*h<sub>1</sub> + ρ*(<sup>V<sub>1</sub><sup>2</sup></sup>⁄<sub>2</sub>) = P<sub>2</sub> + ρ*g*h<sub>2</sub> + ρ*(<sup>V<sub>2</sub><sup>2</sup></sup>⁄<sub>2</sub>) + ρ*F</h2>
</center>
<br />
<div class="data">
<form>
<div class="left">P<sub>1</sub>:
<input id="p1" type="text" size="3" />
</div>
<div class="right">P<sub>2</sub>:
<input id="p2" type="text" size="3" />
</div>
<div class="left">h<sub>1</sub>:
<input id="h1" type="text" size="3" />
</div>
<div class="right">h<sub>2</sub>:
<input id="h2" type="text" size="3" />
</div>
<div class="left">V<sub>1</sub>:
<input id="v1" type="text" size="3" />
</div>
<div class="right">V<sub>2</sub>:
<input id="v2" type="text" size="3" />
</div>
<div class="center">ρ:
<input id="rho" type="text" size="3" />
</div>
<br />
<div class="center">F:
<input id="F" type="text" size="3" />
</div>
<br />
<div class="center">g:
<input id="g" type="text" size="3" value="9.8" />
</div>
<br />
<input id="btn" type="button" value="Calculate" />
</form>
</div>
</div>
JavaScript:
function calculate() {
var p1 = parseFloat(document.getElementById("p1").value, 10);
var p2 = parseFloat(document.getElementById("p2").value, 10);
var h1 = parseFloat(document.getElementById("h1").value, 10);
var h2 = parseFloat(document.getElementById("h2").vaule, 10);
var v1 = parseFloat(document.getElementById("v1").value, 10);
var v2 = parseFloat(document.getElementById("v2").value, 10);
var rho = parseFloat(document.getElementById("rho").value, 10);
var F = parseFloat(document.getElementById("F").value, 10);
var g = parseFloat(document.getElementById("g").value, 10);
var Lside = p1 + (rho * g * h1) + (rho * ((v1 ^ 2) / 2));
var Rside = p2 + (rho * g * h2) + (rho * ((v2 ^ 2) / 2)) + (rho * F);
var ans;
if (!p1) {
ans = Rside - (rho * ((v1 ^ 2) / 2)) - (rho * g * h1);
document.getElementById("p1").value = Math.round(ans * 100) / 100;
} else if (!h1) {
ans = (Rside - (rho * ((v1 ^ 2) / 2)) - p1) / (rho * g);
document.getElementById("h1").value = Math.round(ans * 100) / 100;
} else if (!v1) {
ans = (Rside - p1 - (rho * g * h1)) / rho;
ans = ans * 2;
ans = Math.sqrt(ans);
document.getElementById("v1").value = Math.round(ans * 100) / 100;
} else if (!p2) {
ans = Lside - (rho * ((v2 ^ 2) / 2)) - (rho * g * h2) - (rho * F);
document.getElementById("p2").value = Math.round(ans * 100) / 100;
} else if (!h2) {
ans = (Lside - (rho * ((v2 ^ 2) / 2)) - (rho * F) - p2) / (rho * g);
document.getElementById('h2').value = Math.round(ans * 100) / 100;
}
}
var btn = document.getElementById('btn');
btn.onclick = calculate;
CSS:
.container {
text-align: center;
}
.data {
width: 300px;
margin-left: auto;
margin-right: auto;
}
.left {
text-align: left;
}
.right {
position: relative;
top: -20px;
text-align: right;
}