I'm trying to get one button to fire two functions. It's a basic dice based game: the player die on top works fine, but the computer die doesn't give a value.
function Welcome()
{
alert("Welcome " + document.getElementById("fname").value + "!");
}
function oldEnough(age)
{
if (age< 18)
{alert("UNDER 18 LEAVE NOW");
}
}
//player dice roll//
function rollDice() {
var die1 = document.getElementById("die1");
var die2 = document.getElementById("die2");
var status = document.getElementById("status");
//random number between 1 and 6(whole number)//
var d1 = Math.floor(Math.random() * 6) + 1;
var d2 = Math.floor(Math.random() * 6) + 1;
var diceTotal = d1 + d2;
//shows the random number value//
die1.innerHTML = d1;
die2.innerHTML = d2;
status.innerHTML = "You Rolled "+diceTotal+".";
if (d1 == d2){
status.innerHTML +=" Doubles! Roll Again ";
}
}
//computer dice roll//
function compDice() {
var die3 = document.getElementById("die3")
var die4 = document.getElementById("die4")
var status2 = document.getElementById("status2")
var d3 = Math.floor(Math.random() *6) +1;
var d4 = Math.floor(Math.random() * 6) +1;
var diceTotal = d3 + d4;
die3.innerHTML = d3;
die4.innerHTML = d4;
status2.innerHTML = "Computer Rolled "+diceTotal+".";
}
div.dice{
float:left;
width:32px:
background:#D6D6D6;
border:#999 1px solid;
padding:10px;
font-size:24px;
text-align:center;
margin:5px;
}
div.die{
float:left;
width:32px:
background:#D6D6D6;
border:#999 1px solid;
padding:10px;
font-size:24px;
text-align:center;
margin:5px;
}
<form action="#" method="get">
<p>
Player Name:
<input id="fname" name="fname" type="text" size="20" maxlength="20" onblur="Welcome()" />
</p>
Age:
<input id="age" name="age" id="age" type="text" size="3" maxlength="3" onBlur="oldEnough(this.value)"/>
</p>
<div id="die1" class="dice">0</div>
<div id="die2" class="dice">0</div>
<button onclick="rollDice()";"compDice()">Roll Dice</button>
<h2 id="status" style="clear:left;"></h2>
<div id="die3" class="die">0</div>
<div id="die4" class="die">0</div>
<h2 id="status2" style="clear:right;"></h2>
Change this:
<button onclick="rollDice()";"compDice()">Roll Dice</button>
to:
<button onclick="rollDice();compDice()">Roll Dice</button>
Related
Currently I have two pages the CarRace.html the second is JavaScript.js. CarRace contains three buttons and two images (each is a picture of a car). When the StartRace button is clicked, a random number is to be generated for each car and is to repeat every second. The two numbers generated is the distance each image should move. Currently nothing moves.
CarRace Code:
var timer;
var ArandomNumber;
var BrandonNumber;
var x = 0
var q = 0
function GatherData() {
ArandomNumber = GetRandomNumA();
BrandonNumber = GetRandomNumB();
var thedivtop = document.getElementById("Move1");
x += 10;
thedivtop.style.left = x + 'px';
var thedivbottom = document.getElementById("Move2");
q += 10;
thedivbottom.style.left = q + 'px';
}
function StartRace() {
timer = setInterval(GatherData, 1000);
}
function GetRandomNumA() {
var x = Math.random();
x = Math.random() + 55;
return x;
}
function GetRandomNumB() {
var q = Math.random();
q = Math.random() + 55;
return q;
}
<title>Race</title>
<script src="JavaScript.js"></script>
<style>
.moveable {
position: absolute;
height: 100px;
width: 200px;
}
</style>
</head>
<body>
<b>First to 800 pixels wins!</b>
<br>
<br>
<b>Both cars start at 0 pixels.</b>
<br>
<br>
<input id="Button1" type="button" value="Start Race" onclick="StartRace()" />
<input id="Button1" type="button" value="Pause Race" onclick="PauseRace()" />
<input id="Button1" type="button" value="Reset Cars" onclick="ResetRace()" />
<br>
<br>
<div id="Move1">
<img id="Car1" class="moveable" src="delorean.jpeg" />
</div>
<br>
<br>
<br>
<br>
<br>
<br>
<div id="Move2">
<img id="Car2" class="moveable" src="duster.jpg" />
</div>
</body>
Your JavaScript code does change the cars' left property, however you need to modify your CSS in order to allow the left property take effect.
After adding relative position to the cars elements, they move as expected.
var timer;
var ArandomNumber;
var BrandonNumber;
var x = 0
var q = 0
function GatherData() {
ArandomNumber = GetRandomNumA();
BrandonNumber = GetRandomNumB();
var thedivtop = document.getElementById("Move1");
x += 10;
thedivtop.style.left = x + 'px';
var thedivbottom = document.getElementById("Move2");
q += 10;
thedivbottom.style.left = q + 'px';
}
function StartRace() {
timer = setInterval(GatherData, 1000);
}
function GetRandomNumA() {
var x = Math.random();
x = Math.random() + 55;
return x;
}
function GetRandomNumB() {
var q = Math.random();
q = Math.random() + 55;
return q;
}
#Move1, #Move2 {
position: relative;
}
<title>Race</title>
<script src="JavaScript.js"></script>
<style>
.moveable {
position: absolute;
height: 100px;
width: 200px;
}
</style>
</head>
<body>
<b>First to 800 pixels wins!</b>
<br>
<br>
<b>Both cars start at 0 pixels.</b>
<br>
<br>
<input id="Button1" type="button" value="Start Race" onclick="StartRace()" />
<input id="Button1" type="button" value="Pause Race" onclick="PauseRace()" />
<input id="Button1" type="button" value="Reset Cars" onclick="ResetRace()" />
<br>
<br>
<div id="Move1">
<img id="Car1" class="moveable" src="delorean.jpeg" />
</div>
<br>
<br>
<br>
<br>
<br>
<br>
<div id="Move2">
<img id="Car2" class="moveable" src="duster.jpg" />
</div>
</body>
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I am a first year programming student, so I am sorry if this questions seems a little nooby.
I have created a Calorie Calculator and am having an issue displaying the end result (how many calories they need to take in/let out to reach their desired weight). Also, I apologize for the inline CSS, please ignore it. Any help would be greatly appreciated!
EDIT: Added HTML,JS snippet (sorry about that!). I am still having issues with getting the end result to display.
//var weight = document.getElementById("weight").value;
function getCalc() {
var weight = document.querySelector('.weight');
//var height = document.getElementById("height").value;
var height = document.querySelector('.height');
//var age = document.getElementById("age").value;
var age = document.querySelector('.weight');
//var goalweight = document.getElementById("goalweight").value;
var goalweight = document.querySelector('.goalweight');
//var gender = document.getElementById("gender").value;
var gender = document.querySelector('.gender');
//var activity = document.getElementById("activity").value;
var activity = document.querySelector('.activity');
var BMR = " ";
var BMRGoal = " ";
var dailyCalories = " ";
var goalCalories = " ";
if (gender == "male") {
BMR = 66.47+(6.24*weight)+(12.7*height)-(6.755*age);
BMRGoal = 66.47+(6.24*goalweight)+(12.7*height)-(6.755*age);
} else {
BMR = 655.1+(4.35*weight)+(4.7*height)-(4.7*age);
BMRGoal = 66.47+(6.24*goalweight)+(12.7*height)-(6.755*age);
}
if (activity == "none") {
dailyCalories = BMR*1.2;
goalCalories = BMRGoal*1.2;
} else if (activity == 'light') {
dailyCalories = BMR*1.375;
goalCalories = BMRGoal*1.2;
} else if (activity == 'moderate') {
dailyCalories = BMR*1.55;
goalCalories = BMRGoal*1.2;
} else if (activity == 'heavy') {
dailyCalories = BMR*1.725;
goalCalories = BMRGoal*1.2;
} else if (activity == 'xheavy') {
dailyCalories = BMR*1.9;
goalCalories = BMRGoal*1.2;
}
document.getElementByClassName('requireddailycals').innerHTML = 'Your current daily calorie intake is ' + dailyCalories + '. In order to reach your desired weight goal, you will need to increase your caloric intake to ' + goalCalories + '.';
document.getElementById("requireddailycals").value = dailyCalories(goalCalories);
}
<!DOCTYPE html>
<html>
<head>
<title>Nutrition Calculator</title>
<style>
body {
background-color:rgba(102,143,74, 0.3);
}
a {
text-decoration:none;
}
.calcalc_box {
position:absolute;
margin:auto;
top:35vh;
transform:translateY(-35%);
left:50vw;
transform:translateX(-50%);
border:0.2vw solid #a6b727;
text-align:center;
padding:5vw;
font-family:Arial;
box-shadow:0.5vw 0.5vh 0 #a6b727;
}
.calcalc_box > h1 {
font-family:Lucida Console;
color:#316886;
font-size:3vw;
}
.calcalc_box > h2 {
color:#a6b727;
margin:5vh 0 5vh 0;
}
.calcalc_logo {
margin:auto;
}
.calcalc_button {
background-color:#a6b727;
color:black;
padding:0.8vw;
font-size:1.3vw;
font-weight:bold;
border:0.2vw solid #a6b727;
margin:0.5vw;
display:inline-block;
border-radius:0.3vw;
}
.calcalc_button:hover {
background-color:rgba(102,143,74, 0.3);
}
label {
display:inline;
color:#a6b727;
font-weight:bold;
}
.the_calculator {
border:0.2vw solid #a6b727;
text-align:left;
padding:0.5vw;
}
.calculator_section {
display:inline-block;
margin:1vw 0 1vw 0;
width:100%;
}
.calculator_section > label {
font-weight:bold;
padding:0.5vw;
}
.calculator_input {
padding:0.5vw;
margin-bottom:2vw;
}
.calcalc_back {
color:#a6b727;
font-weight:bold;
padding:2vw;
}
</style>
</head>
<body>
<div class="calcalc_box">
<img src="calcalc.png" width="250" height="250" />
<h1>Cal-Calc</h1>
<h2>Nutrition Calculator</h2>
<form class="the_calculator">
<div class="calculator_section">
<label for="gender">Gender</label>
Male<input type="radio" name="gender" value="Male" id="gender">
Female<input type="radio" name="gender" value="Female" id="gender">
</div>
<label for="age">Age : </label><input type="number" name="age" class="calculator_input" id="age"><br>
<label for="height">Height (in inches) : </label><input type="number" name="height" class="calculator_input" id="height"><br>
<label for="weight">Weight (in pounds) : </label><input type="number" name="weight" class="calculator_input" id="weight"><br>
<label for="goalweight">Goal Weight : </label><input type="number" name="weight" class="calculator_input" id="goalweight"><br>
<label for="activity">Activity Level</label>
Little to no exercise <input type="radio" name="activity" value="none" id="activity">
Light Exercise (walks, runs) <input type="radio" name="activity" value="light" id="activity">
Moderate Exercise (sports) <input type="radio" name="activity" value="moderate" id="activity">
Heavy Exercise (daily consistent routine) <input type="radio" name="activity" value="heavy" id="activity">
Extra Heavy Exercise (twice daily consistent routine) <input type="radio" name="activity" value="xheavy" id="activity">
<br><br>
<button class="calcalc_button" onClick="getCalc()" style="margin-left:13vw;" >Calculate
</button>
<span class= "requireddailycals"></span>
</form>
<span class="calcalc_back"><br><br><br>click here to go back</span>
</div>
<script src="./project.js">
</script>
</body>
</html>
In your HTML you have:
<span class= "requireddailycals"/span>
Try instead:
<span class= "requireddailycals"></span>
Then change the JS this way:
document.getElementsByClassName("requireddailycals")[0].innerHTML = 'Your current daily calorie intake is ' + dailyCalories + '. In order to reach your desired weight goal, you will need to increase your caloric intake to ' + goalCalories + '.';
or better, get the element by id
NB: try to use the JS/HTML/CSS snipped to allow use to run your code more easily.
I used an eventListener() with preventDefault(). You can also add a type="button" to your calculate button if you continue to use an inline HTML event attributes but that is not recommended.
I also changed your querySelector because you were attempting to select an element by id, and you were using a class as a selector.
You also had a minor typo, which did not break your code.
This will solve your problem:
document.querySelector('.calcalc_button').addEventListener('click', function(e) {
e.preventDefault();
var weight = document.getElementById('weight').value;
var height = document.getElementById("height").value;
var age = document.getElementById("age").value;
var goalweight = document.getElementById("goalweight").value;
var gender = document.getElementById("gender").value;
var activity = document.getElementById("activity").value;
var BMR = " ";
var BMRGoal = " ";
var dailyCalories = " ";
var goalCalories = " ";
if (gender == "male") {
BMR = 66.47+(6.24*weight)+(12.7*height)-(6.755*age);
BMRGoal = 66.47+(6.24*goalweight)+(12.7*height)-(6.755*age);
} else {
BMR = 655.1+(4.35*weight)+(4.7*height)-(4.7*age);
BMRGoal = 66.47+(6.24*goalweight)+(12.7*height)-(6.755*age);
}
if (activity == "none") {
dailyCalories = BMR*1.2;
goalCalories = BMRGoal*1.2;
} else if (activity == 'light') {
dailyCalories = BMR*1.375;
goalCalories = BMRGoal*1.2;
} else if (activity == 'moderate') {
dailyCalories = BMR*1.55;
goalCalories = BMRGoal*1.2;
} else if (activity == 'heavy') {
dailyCalories = BMR*1.725;
goalCalories = BMRGoal*1.2;
} else if (activity == 'xheavy') {
dailyCalories = BMR*1.9;
goalCalories = BMRGoal*1.2;
}
document.querySelector('.requireddailycals').innerHTML = 'Your current daily calorie intake is ' + dailyCalories + '. In order to reach your desired weight goal, you will need to increase your caloric intake to ' + goalCalories + '.';
//document.getElementById("requireddailycals").value = dailyCalories(goalCalories);
})
//var weight = document.getElementById("weight").value;
function getCalc() {
preventDefault();
console.log("asd");
}
body {
background-color:rgba(102,143,74, 0.3);
}
a {
text-decoration:none;
}
.calcalc_box {
position:absolute;
margin:auto;
top:35vh;
transform:translateY(-35%);
left:50vw;
transform:translateX(-50%);
border:0.2vw solid #a6b727;
text-align:center;
padding:5vw;
font-family:Arial;
box-shadow:0.5vw 0.5vh 0 #a6b727;
}
.calcalc_box > h1 {
font-family:Lucida Console;
color:#316886;
font-size:3vw;
}
.calcalc_box > h2 {
color:#a6b727;
margin:5vh 0 5vh 0;
}
.calcalc_logo {
margin:auto;
}
.calcalc_button {
background-color:#a6b727;
color:black;
padding:0.8vw;
font-size:1.3vw;
font-weight:bold;
border:0.2vw solid #a6b727;
margin:0.5vw;
display:inline-block;
border-radius:0.3vw;
}
.calcalc_button:hover {
background-color:rgba(102,143,74, 0.3);
}
label {
display:inline;
color:#a6b727;
font-weight:bold;
}
.the_calculator {
border:0.2vw solid #a6b727;
text-align:left;
padding:0.5vw;
}
.calculator_section {
display:inline-block;
margin:1vw 0 1vw 0;
width:100%;
}
.calculator_section > label {
font-weight:bold;
padding:0.5vw;
}
.calculator_input {
padding:0.5vw;
margin-bottom:2vw;
}
.calcalc_back {
color:#a6b727;
font-weight:bold;
padding:2vw;
}
<div class="calcalc_box">
<img src="https://placekitten.com/200/300" width="250" height="250" />
<h1>Cal-Calc</h1>
<h2>Nutrition Calculator</h2>
<form class="the_calculator">
<div class="calculator_section">
<label for="gender">Gender</label>
Male<input type="radio" name="gender" value="Male" id="gender">
Female<input type="radio" name="gender" value="Female" id="gender">
</div>
<label for="age">Age : </label><input type="number" name="age" class="calculator_input" id="age"><br>
<label for="height">Height (in inches) : </label><input type="number" name="height" class="calculator_input" id="height"><br>
<label for="weight">Weight (in pounds) : </label><input type="number" name="weight" class="calculator_input" id="weight"><br>
<label for="goalweight">Goal Weight : </label><input type="number" name="weight" class="calculator_input" id="goalweight"><br>
<label for="activity">Activity Level</label>
Little to no exercise <input type="radio" name="activity" value="none" id="activity">
Light Exercise (walks, runs) <input type="radio" name="activity" value="light" id="activity">
Moderate Exercise (sports) <input type="radio" name="activity" value="moderate" id="activity">
Heavy Exercise (daily consistent routine) <input type="radio" name="activity" value="heavy" id="activity">
Extra Heavy Exercise (twice daily consistent routine) <input type="radio" name="activity" value="xheavy" id="activity">
<br><br>
<button class="calcalc_button" style="margin-left:13vw;" >Calculate</button>
<span class= "requireddailycals"></span>
</form>
<span class="calcalc_back"><br><br><br>click here to go back</span>
</div>
Ive been trying to add a discount to price classes for a couple of days now but haven’t been able to. The current js code I have is a simple addition calculator, but I want it to discount prices between 100 and 500 with 10% and prices over 500 get 20% discount. I also want it to show the price before and after the discount if possible.
The code I have for the calculator so far, its working fine:
function calculate() {
var field1 = document.getElementById("num1").value;
var field2 = document.getElementById("num2").value;
var result = parseFloat(field1) + parseFloat(field2);
if (!isNaN(result)) {
document.getElementById("answer").innerHTML = "Totalpris är " + result;
}
}
Artikel 1 <input type="text2" id="num1">
<br>
<br> Artikel 2 <input type="text2" id="num2">
<br>
<br>
<button onclick="calculate()">Totalpris</button>
<h1 id="answer"></h1>
This is pretty simple to do with some if statements.
function calculate() {
var field1 = document.getElementById("num1").value;
var field2 = document.getElementById("num2").value;
var beforeDiscount = parseFloat(field1) + parseFloat(field2);
var afterDiscount = beforeDiscount;
if (beforeDiscount >= 100 && beforeDiscount < 500) {
afterDiscount = beforeDiscount * 0.9;
} else if (beforeDiscount >= 500) {
afterDiscount = beforeDiscount * 0.8;
}
if (!isNaN(beforeDiscount)) {
document.getElementById("answer").innerHTML =
"Totalpris är "+afterDiscount+". Was "+beforeDiscount;
}
}
Artikel 1 <input type="text2" id="num1">
<br>
<br>
Artikel 2 <input type="text2" id="num2">
<br>
<br>
<button onclick="calculate()">Totalpris</button>
<h1 id="answer"></h1>
You should give type number
text2 is not a valid value for the type attribute
Instead of this
Artikel 1 <input type="text2" id="num1">
<br>
<br>
Artikel 2 <input type="text2" id="num2">
Do this
<input type ="number" id="num1">
<input type="number" id="num2">
Here is the solution for your challenge
<!DOCTYPE html>
<html>
<head>
</head>
<body>
a.htmlArtikel 1 <input id="num1" type="number">
<br>
<br>
Artikel 2 <input type="number" id="num2">
<br>
<br>
<button onclick="calculate()">Totalpris</button>
<script>
function calculate(){
let result = ``;
const field1 = document.getElementById("num1").value;
const field2 = document.getElementById("num2").value;
let amount_before_discount = parseFloat(field1)+parseFloat(field2);
let amount_after_discount = amount_before_discount
if(amount_after_discount >= 100 && amount_before_discount < 500){
amount_after_discount = amount_before_discount * 0.9;
// for the second question, look at the comments
result += `After an discount of 10% the new price is
${amount_after_discount}`
}else if(amount_before_discount >= 500){
amount_after_discount = amount_before_discount * 0.8;
result += `After an discount of 20% the new price is
${amount_after_discount}`
}
if (!isNaN(amount_before_discount)) {
// here you can innerHtml then the result
document.getElementById("answer").innerHTML =
"Totalpris är "+amount_after_discount+". Was "+amount_before_discount;
}
}
</script>
<h1 id="answer"></h1>
</body>
</html>
I have a situation where user may insert the Total Quantity and also the Total Pass and Total Fail. I have created a function where when the number of Total Pass inserted, the loop (of entering the pass score) will run according to the iterations inputted.
However, I do not want to have the loop to display the line Enter The Score : in the JavaScript function. Therefore, I want the function to call a div from the HTML itself.
For example, I want the <div id="outputPass"><p>Enter the score : <input type="text" /></p></div> to be called in the loop function which I have created in the document.getElementById('btnPass').onclick = function().
I have inserted some comments in the code section.
document.getElementById('btnPass').onclick = function() {
var totalIterations = parseInt(document.getElementById('inputPass').value);
var output = document.getElementById('outputPass');
var quantity = document.getElementById('quantity').value;
output.innerHTML = '';
if (quantity < totalIterations) {
alert("Invalid Input, Pass Value(" + totalIterations + ") Bigger than Quantity(" + quantity + ")");
} else {
for (var i = 1; i <= totalIterations; i++) {
var item = document.createElement('div');
//Call <div> from HTML
item.innerHTML = "";
output.appendChild(item);
}
}
};
document.getElementById('btnFail').onclick = function() {
var totalIterations = parseInt(document.getElementById('inputFail').value);
var output = document.getElementById('outputFail');
var quantity = document.getElementById('quantity').value;
output.innerHTML = '';
if (quantity < totalIterations) {
alert("Invalid Input, Fail Value(" + totalIterations + ") Bigger than Quantity(" + quantity + ")");
} else {
for (var i = 1; i <= totalIterations; i++) {
var item = document.createElement('div');
//Call <div> from HTML
item.innerHTML = "";
output.appendChild(item);
}
}
};
function togglePass() {
var x = document.getElementById("passDiv");
if (x.style.display === "block") {
x.style.display = "none";
} else {
x.style.display = "block";
}
}
function toggleFail() {
var y = document.getElementById("failDiv");
if (y.style.display === "block") {
y.style.display = "none";
} else {
y.style.display = "block";
}
}
.display {
display: none;
}
<form method="post" name="form">
<p>Enter the quantity : <input type="text" id="quantity" name="quantity" /></p><br />
<input type="button" value="Pass" onclick="togglePass()">
<input type="button" value="Fail" onclick="toggleFail()">
<div id="passDiv" class="display">
<p>Enter Total Pass : <input type="text" id="inputPass" name="inputPass" /> <input type="button" value="Key In Score" id="btnPass" onclick="return validate();"></p><br />
<!--This Div-->
<div id="outputPass">
<p>Enter the score : <input type="text" /></p>
</div>
<br />
<input type="button" value="DONE">
</div>
<br />
<div id="failDiv" class="display">
<p>Enter Total Fail : <input type="text" id="inputFail" /> <input type="button" value="Key In Score" id="btnFail"></p><br />
<!--This Div-->
<div id="outputFail">
<p>Enter the score : <input type="text" /></p>
</div>
<br />
<input type="button" value="DONE">
</div>
</form>
You can make the following changes to achieve what you are looking for:
Initially we're giving an id of pscore/fscore (for pass and fail respectively) to the <p></p> tags and hiding them.
<p id="fscore" style="display:none">Enter the score : <input type="text" /></p>
We're accessing them in the javascript code in the form of variables pscore and fscore respectively. (Make sure they are declared globally outside)
var pscore = document.getElementById('pscore');
var fscore = document.getElementById('fscore');
Then in the iterations we can just make a clone of the pscore/fscore , give a class of pscore/fscore to the <p></p> tags and remove the id of pscore/score (to avoid duplicate IDs), changing the display to block and append it to the output container by using the following:
var cln = pscore.cloneNode(true);
cln.style.display="block";
cln.className ="pscore";
cln.removeAttribute("id");
item.appendChild(cln);
var cln = fscore.cloneNode(true);
cln.style.display="block";
cln.removeAttribute("id");
cln.className ="fscore";
item.appendChild(cln);
var pscore = document.getElementById('pscore');
var fscore = document.getElementById('fscore');
document.getElementById('btnPass').onclick = function() {
var totalIterations = parseInt(document.getElementById('inputPass').value);
var output = document.getElementById('outputPass');
var quantity = document.getElementById('quantity').value;
output.innerHTML = '';
if (quantity < totalIterations) {
alert("Invalid Input, Pass Value(" + totalIterations + ") Bigger than Quantity(" + quantity + ")");
} else {
for (var i = 1; i <= totalIterations; i++) {
var item = document.createElement('div');
//Call <div> from HTML
var cln = pscore.cloneNode(true);
cln.style.display = "block";
cln.className = "pscore";
cln.removeAttribute("id");
item.appendChild(cln);
output.appendChild(item);
}
}
};
document.getElementById('btnFail').onclick = function() {
var totalIterations = parseInt(document.getElementById('inputFail').value);
var output = document.getElementById('outputFail');
var quantity = document.getElementById('quantity').value;
output.innerHTML = '';
if (quantity < totalIterations) {
alert("Invalid Input, Fail Value(" + totalIterations + ") Bigger than Quantity(" + quantity + ")");
} else {
for (var i = 1; i <= totalIterations; i++) {
var item = document.createElement('div');
//Call <div> from HTML
var cln = fscore.cloneNode(true);
cln.style.display = "block";
cln.className = "fscore";
cln.removeAttribute("id");
item.appendChild(cln);
output.appendChild(item);
}
}
};
function togglePass() {
var x = document.getElementById("passDiv");
if (x.style.display === "block") {
x.style.display = "none";
} else {
x.style.display = "block";
}
}
function toggleFail() {
var y = document.getElementById("failDiv");
if (y.style.display === "block") {
y.style.display = "none";
} else {
y.style.display = "block";
}
}
.display {
display: none;
}
<form method="post" name="form">
<p>Enter the quantity : <input type="text" id="quantity" name="quantity" /></p><br />
<input type="button" value="Pass" onclick="togglePass()">
<input type="button" value="Fail" onclick="toggleFail()">
<div id="passDiv" class="display">
<p>Enter Total Pass : <input type="text" id="inputPass" name="inputPass" /> <input type="button" value="Key In Score" id="btnPass"></p><br />
<!--This Div-->
<div id="outputPass">
<p id="pscore" style="display:none">Enter the score : <input type="text" /></p>
</div>
<br />
<input type="button" value="DONE">
</div>
<br />
<div id="failDiv" class="display">
<p>Enter Total Fail : <input type="text" id="inputFail" /> <input type="button" value="Key In Score" id="btnFail"></p><br />
<!--This Div-->
<div id="outputFail">
<p id="fscore" style="display:none">Enter the score : <input type="text" /></p>
</div>
<br />
<input type="button" value="DONE">
</div>
</form>
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;
}