I have been recently working on a project which demonstrates the use of the arithmetic sequence. The user will use a slider to input the value for the starting term, which is t0; the difference, which is d; the number of terms, which is represented as n. However, I could not get the code to work. I used the solution in this post: HTML5 input type range show range value . A demo of my code down below:
var t0, difference, boxedNums, numOfTerms, redCircle, redTriangle, redRectangle, blueCircle, blueTriangle, blueRectangle;
function genTn() {
reset();
t0 = document.getElementById("t0").value;
difference = document.getElementById("d").value;
numOfTerms = document.getElementById("tn").value;
var tn;
document.getElementById('buildButton').style.display = 'none';
for (n = 0; n < numOfTerms; n++) {
tn = t0 * 1 + difference * n;
setTimeout(buildNextOne, 3000 * n, n, tn);
}
setTimeout(showButton, 3000 * numOfTerms);
document.getElementById("formulat0").innerHTML = t0;
document.getElementById("formulad").innerHTML = difference;
document.getElementById("formulan").innerHTML = numOfTerms;
}
function buildNextOne(n, tn) {
var insert = '<div class="col-sm-4 col-md-2 boxed center">'
insert += 't<sub>' + n + '</sub><br>'
insert += '<span class="tn">' + tn + '</span><br>'
insert += getPicsRepresentOfNumber(tn);
insert += '</div>'
document.getElementById("boxArea").innerHTML += insert;
var msg = new SpeechSynthesisUtterance(tn);
window.speechSynthesis.speak(msg);
}
function showButton() {
document.getElementById('buildButton').style.display = '';
}
function reset() {
document.getElementById("boxArea").innerHTML = "";
}
function getPicsRepresentOfNumber(number) {
var totalHund = 0,
totalTens = 0,
totalOnes = 0,
returnHtml = '';
totalHund = Math.abs(parseInt(number / 100));
var diffAfterRemovingHund = number % 100;
totalTens = Math.abs(parseInt(diffAfterRemovingHund / 10));
totalOnes = Math.abs(parseInt(diffAfterRemovingHund % 10));
for (var i = 0; i < totalHund; i++) {
returnHtml += number < 0 ? "<img src='imgs/negativeHundred.png'> " : "<img src='imgs/hundred.png'> ";
if (i == 4) {
returnHtml += " "
}
}
returnHtml += "<br>";
for (var i = 0; i < totalTens; i++) {
returnHtml += number < 0 ? "<img src='imgs/negativeTen.png'> " : "<img src='imgs/ten.png'> ";
if (i == 4) {
returnHtml += " ";
}
}
returnHtml += "<br>";
for (var i = 0; i < totalOnes; i++) {
returnHtml += number < 0 ? "<img src='imgs/negativeOne.png'> " : "<img src='imgs/one.png'> ";
if (i == 4) {
returnHtml += " ";
}
}
returnHtml += "<br>";
return returnHtml;
}
function updateT0Input(t0) {
document.getElementById("updatet0").value = t0;
}
function updateDInput(difference) {
document.getElementById("updated").value = difference;
}
function updateNInput(numOfTerms) {
document.getElementById("updaten").value = numOfTerms;
}
.center {
text-align: center;
}
#equation {
background-color: lightgreen;
text-align: center;
border-radius: 10%;
}
body {
background-color: lightblue;
}
#formula {
background-color: lightgreen;
}
.boxed {
border: 1px solid gray;
margin-top: 10px;
background-color: beige;
}
.tn {
font-size: 3em;
}
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css"
integrity="sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS" crossorigin="anonymous">
<link rel="stylesheet" href="style.css">
<title>Assignment 10a2</title>
</head>
<body>
<div id="formula">
Formula: <br>
t<sub>n</sub> = <span id="formulat0">t<sub>0</sub></span> + <span id="formulad">d</span>*<span id='formulan'>n</span> <br>
<br>
t<sub>0</sub> = <span id="updatet0"></span>
<input type="range" min="-50" max="50" value="0" id="t0" class="slider" onchange="updateT0Input(this.value);">
<br>
d = <span id="updated"></span>
<input type="range" min="-50" max="50" value="0" id="d" class="slider" onchange="updateDInput(this.value);">
<br>
n = <span id="updaten"></span>
<input type="range" min="1" max="20" value="10" id="tn" class="slider" onchange="updateNInput(this.value);">
<br>
<button id="buildButton" style="display:''" type="button" class="btn btn-warning"
onclick="genTn()">Generate</button>
</div>
<br>
<div class="container">
<div class="row" id="boxArea">
</div>
</div>
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"
integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo"
crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js"
integrity="sha384-wHAiFfRlMFy6i5SRaxvfOCifBUQy1xHdJ/yoi7FRNXMRBu5WHdZYu1hA6ZOblgut"
crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js"
integrity="sha384-B0UglyR+jN6CkvvICOB2joaf5I4l3gm9GU6Hc1og6Ls7i6U/mkkaduKaBhlAXv9k"
crossorigin="anonymous"></script>
<script src="10a2.js"></script>
</body>
I added the functions updateT0Input, updateDInput, and updateNInput:
function updateT0Input(t0) {
document.getElementById("updatet0").value = t0;
}
function updateDInput(difference) {
document.getElementById("updated").value = difference;
}
function updateNInput(numOfTerms) {
document.getElementById("updaten").value = numOfTerms;
}
And my html slidebars are here:
t<sub>0</sub> = <span id="updatet0"></span>
<input type="range" min="-50" max="50" value="0" id="t0" class="slider" onchange="updateT0Input(this.value);">
<br>
d = <span id="updated"></span>
<input type="range" min="-50" max="50" value="0" id="d" class="slider" onchange="updateDInput(this.value);">
<br>
n = <span id="updaten"></span>
<input type="range" min="1" max="20" value="10" id="tn" class="slider" onchange="updateNInput(this.value);">
Did I do something wrong?
Please do not mind the undisplayable images in the demo
JSFiddle with your code snippet: https://jsfiddle.net/u92ws7ce/1/
Here's your HTML with slightly modified class names:
t<sub>0</sub> = <span id="updatet0"></span>
<input type="range" min="-50" max="50" value="0" id="t0" class="slider1" onchange="updateT0Input(this.value);">
<p>Value: <span id="demo1"></span></p>
<br>
d = <span id="updated"></span>
<input type="range" min="-50" max="50" value="0" id="d" class="slider2" onchange="updateDInput(this.value);">
<p>Value: <span id="demo2"></span></p>
<br>
n = <span id="updaten"></span>
<input type="range" min="1" max="20" value="10" id="tn" class="slider3" onchange="updateNInput(this.value);">
<p>Value: <span id="demo3"></span></p>
And add this to your JS file:
var output1 = document.getElementById("demo1");
output1.innerHTML = slider1.value;
slider1.oninput = function() {
output1.innerHTML = this.value;
}
var slider2 = document.getElementById("d");
var output2 = document.getElementById("demo2");
output2.innerHTML = slider2.value;
slider2.oninput = function() {
output2.innerHTML = this.value;
}
var slider3 = document.getElementById("tn");
var output3 = document.getElementById("demo3");
output3.innerHTML = slider3.value;
slider3.oninput = function() {
output3.innerHTML = this.value;
}
Make sure you identify each slider with a unique class name and id. You'll want to refactor it to be programmatic and use functions to encapsulate repetitive logic.
Reference: https://www.w3schools.com/howto/howto_js_rangeslider.asp
Related
I try to build a boxShadow generator, where the user can add multiple layers of boxShadow. Anything like the example below:
box-shadow: rgba(50, 50, 93, 0.25) 0px 13px 27px -5px, rgba(0, 0, 0, 0.3) 0px 8px 16px -8px;
What I have so far:
A constructor function, which creates my shadows.
function Shadow(paramId) {
this.shadowId = paramId;
this.horizontalValue = 'horizontalRange' + paramId;
this.verticalValue = 'verticalRange' + paramId;
this.blurValue = 'blurRange' + paramId;
this.spreadValue = 'spreadRange' + paramId;
this.colorValue = 'colorInput' + paramId;
}
...and a function, which gets the value of the sliders:
function getRangeValue () {
const shadowBox = document.getElementById('shadowBox');
let shadowId = this.id.slice(this.id.length - 1, this.id.length) - 1; // my Id's are like xOffset1
let xValue = document.getElementById(shadowObjContainer[shadowId].horizontalValue).value;
let yValue = document.getElementById(shadowObjContainer[shadowId].verticalValue).value;
let blurValue = document.getElementById(shadowObjContainer[shadowId].blurValue).value;
let spreadValue = document.getElementById(shadowObjContainer[shadowId].spreadValue).value;
let colorValue = document.getElementById(shadowObjContainer[shadowId].colorValue).value;
shadowParam = `${xValue}px ${yValue}px ${blurValue}px ${spreadValue}px ${colorValue}`;
shadowBox.style.boxShadow = shadowParam;
}
It does work, that my sliders do what they are supposed to do. But I don't know, how to create another shadow parameter (", " + shadowParam).
Hopefully someone can help me.
Thank you :)
A working example to work on was helpful. I hypothesized your environment and this is my commented idea.
// The class with all controls for each shadows
let Control = class {
constructor(paramId) {
this.shadowId = paramId;
this.horizontalValue = 'horizontalRange' + paramId;
this.verticalValue = 'verticalRange' + paramId;
this.blurValue = 'blurRange' + paramId;
this.spreadValue = 'spreadRange' + paramId;
this.colorValue = 'colorInput' + paramId;
}
}
// Generates the shadow for each initialized Control class
function getRangeValue() {
const shadowBox = document.getElementById('shadowBox');
let shadowParam = '';
for (let i = 0; i < Controls.length; i++) {
let shadowId = Controls[i].shadowId;
let xValue = document.getElementById(Controls[i].horizontalValue).value;
let yValue = document.getElementById(Controls[i].verticalValue).value;
let blurValue = document.getElementById(Controls[i].blurValue).value;
let spreadValue = document.getElementById(Controls[i].spreadValue).value;
let colorValue = document.getElementById(Controls[i].colorValue).value;
shadowParam = (shadowParam == '' ? '' : shadowParam + ', ') + `${xValue}px ${yValue}px ${blurValue}px ${spreadValue}px ${colorValue}`;
}
shadowBox.style.boxShadow = shadowParam;
}
// Initialization of the Control classes based on the "group" of controls named "ShadowControls"
let ShadowControlsEl = document.getElementsByClassName("ShadowControls");
let Controls = Array();
for (let i = 0; i < ShadowControlsEl.length; i++) {
Controls.push(new Control(i + 1));
}
// Generate the first Shadows
getRangeValue();
// Initialize listeners for values change
let AllControls = document.getElementsByClassName('listener');
for (let i = 0; i < AllControls.length; i++) {
AllControls[i].addEventListener('change', getRangeValue);
}
#shadowBox {
width: 100px;
height: 100px;
margin: 50px;
background-color:#ff00ff;
}
<div class="ShadowControls">
<input id="horizontalRange1" class="listener" type="range" min="-100" max="100" value="10">
<input id="verticalRange1" class="listener" type="range" min="-100" max="100" value="10">
<input id="blurRange1" class="listener" type="range" min="0" max="100" value="0">
<input id="spreadRange1" class="listener" type="range" min="0" max="100" value="0">
<input id="colorInput1" class="listener" type="color" value="#FF0000">
</div>
<hr>
<div class="ShadowControls">
<input id="horizontalRange2" class="listener" type="range" min="-100" max="100" value="-10">
<input id="verticalRange2" class="listener" type="range" min="-100" max="100" value="-10">
<input id="blurRange2" class="listener" type="range" min="0" max="100" value="0">
<input id="spreadRange2" class="listener" type="range" min="0" max="100" value="0">
<input id="colorInput2" class="listener" type="color" value="#FFFF00">
</div>
<div id="shadowBox">
Shadow here
</div>
I'm building a popup chrome extension that works as a countdown timer, but it is not working as intended. When a user inputs a certain amount of minutes, for instance, seconds will immediately turn to 59 and begin decrementing, but minutes will remain static. The same happens with hours.
This is my html code:
<!DOCTYPE html>
<html lang="en">
<head>
<link href="https://fonts.googleapis.com/css2?family=Montserrat:wght#500&display=swap" rel="stylesheet">
<link href="../stylesheet.css" rel="stylesheet">
<title>Study Break Chrome Extension</title>
<!-- <script src="jquery.js"></script> -->
<script src="../popup-script.js"></script>
<script src="../background.js"></script>
<!-- <script src="timer.html"></script> -->
<style>
body {
font-family: "Monaco", monospace;
color: #003c00;
background-image: url('/media/bg2.JPEG');
background-repeat: no-repeat;
background-attachment: fixed;
background-size: cover;
}
html, body {
text-align: center;
width: 325px;
}
</style>
</head>
<body>
<div class="header">
<h1>Study Break!</h1>
</div>
<div class="container">
<div id="work">
<h2 class = "idk">Set A Break Every...</h2>
<p id="workhrlabel" class="workhrlabel">Hours</p>
<p id="workminlabel" class="workminlabel">Minutes</p>
<p id="workseclabel" class="workseclabel">Seconds</p>
<input id="work-hours" type="number" max="99" min="0" value="0" class="worktime">
<p id="p1" class="semicolon">:</p>
<input id="work-minutes" type="number" max="60" min="0" value="0" class="worktime">
<p id="p2" class="semicolon">:</p>
<input id="work-secs" type="number" max="60" min="0" value="0" class="worktime">
</div>
<div id="break">
<h2>For...</h2>
<p id="break-hour-label" class="break-label">Hours</p>
<p id="break-min-label" class="break-label">Minutes</p>
<p id="break-sec-label" class="break-label">Seconds</p>
<input id="break-hours" type="number" max="99" min="0" value="0" class="breaktime">
<p id="p1" class="semicolon">:</p>
<input id="break-minutes" type="number" max="60" min="0" value="0" class="breaktime">
<p id="p2" class="semicolon">:</p>
<input id="break-secs" type="number" max="60" min="0" value="0" class="breaktime">
</div>
<div class = "btns">
<button id="set" class="btn">Set</button>
<button id="reset" class="btn">Reset</button>
</div>
</body>
</html>
My popup-script:
document.addEventListener('DOMContentLoaded', function(){
document.getElementById('set').addEventListener('click', function(){
let selHrs = document.getElementById('work-hours').value;
let selMins = document.getElementById('work-minutes').value;
let selSecs = document.getElementById('work-secs').value;
chrome.runtime.sendMessage({name: 'Timer', hours: selHrs, mins: selMins, secs: selSecs});
});
})
chrome.runtime.onMessage.addListener(function(request, _, _){
if (request.name == 'updateTimer') {
document.getElementById('work-hours').setAttribute('value', request.hours);
document.getElementById('work-minutes').setAttribute('value', request.mins);
console.log(request.mins)
document.getElementById('work-secs').setAttribute('value', request.secs);
}
});
And my background-script:
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse){
let set = document.getElementById('set');
let hours = request.hours;
let mins = request.mins;
let secs = request.secs;
let startTimer = undefined;
if (request.name == "Timer"){
function countdown(hr,mm,ss)
{
var interval = setInterval(function(){
if(hr == 0 && mm == 0 && ss == 0)clearInterval(interval);
if(ss == 0)
{
ss = 59;
if(mm == 0)
{
mm = 59;
if (hr != 0) {
hr--;
}
}
else {
mm--;
}
} else {
ss--;
}
console.log("hours" + hr + "minutes: " + mm + " secondsL " + ss);
chrome.runtime.sendMessage({name: 'updateTimer', hours: hr, mins: mm, secs: ss});
},1000)
}
countdown(hours, mins, secs)
}
})
Any help will be greatly appreciated!
I am trying to make a calculator in javascript and it is not working. When I try to do, say 1 + 1 it gives me 11 and this is the same for all the numbers here is my code:
var slider1 = document.getElementById("myRange1");
var slider2 = document.getElementById("myRange2");
var output = document.getElementById("output");
var fullEquat = document.getElementById("equation");
var add1 = slider1.value;
var add2 = slider2.value;
output.innerHTML = slider1.value; // Display the default slider value
// Update the current slider value (each time you drag the slider handle)
slider1.oninput = function() {
output.innerHTML = this.value;
}
slider2.oninput = function() {
add1 = slider1.value;
add2 = slider2.value;
equals = add1 + add2;
fullEquat.innerHTML = slider1.value + "+" + slider2.value + "=" + equals;
}
slider1.oninput = function() {
add1 = slider1.value;
add2 = slider2.value;
equals = add1 + add2;
fullEquat.innerHTML = slider1.value + "+" + slider2.value + "=" + equals;
}
.slider {
width: 400px;
display: inline;
}
.equal {
text-align: center;
font-size: 100pt;
margin: 0 0 0 0;
}
<div class="slidecontainer">
<input type="range" min="0" max="1000" value="500" class="slider" id="myRange1">
+
<input type="range" min="0" max="1000" value="500" class="slider" id="myRange2">
</div>
<p class="equal">=</p>
<p id="output" class="output"></p>
<p id="equation" class="equat"> + = </p>
When you declared add1 = slider1.value; add2 = slider2.value; you got a string instead of a number... you should put them inside a Number() like this
add1 = Number(slider1.value);
add2 = Number(slider2.value);
Value property returns you a string, you can use a simple trick to multiply it with 1 like add1 = slider. value * 1. and it will give you a number
.value property return a string
you have to use .valueAsNumber to get a number
sample code:
const calcForm = document.forms['form-calculation']
, pOutput = document.getElementById('p-output')
;
calcForm.oninput=_=>
{
calcForm['range-1'].nextElementSibling.textContent = calcForm['range-1'].value
calcForm['range-2'].nextElementSibling.textContent = calcForm['range-2'].value
pOutput.textContent = calcForm['range-1'].valueAsNumber
+ calcForm['range-2'].valueAsNumber
}
form { width: 20em; }
input[type="range"] {width: 80%; }
label { font-size:2em; font-weight: bold; text-align: center; display: block; width: 80%;}
<form name="form-calculation">
<input type="range" min="0" max="1000" value="500" name="range-1"><span>500</span>
<label>+</label>
<input type="range" min="0" max="1000" value="500" name="range-2"><span>500</span>
<label>=</label>
</form>
<p id="p-output" class="output">1000</p>
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;
}