How to switch functions javascript - javascript

I'd like to make something small. When you enter Celsius, the program should calculate Fahrenheit and vice-versa. But when I enter the celsius and click the button it does the vice-versa aswell. Since I'm a beginner I don't really know how not to execute function2 if function1 activates. My javascript looks like this:
JS:
function Omrekenen() {
var celsius = document.getElementById('Celsius').value;
var fahrenheit = document.getElementById('Fahrenheit').value;
var r1 = (celsius * 1.8) + 32;
var r2 = (fahrenheit / 1.8) - 32;
}
function Leeg1() {
document.getElementById('Fahrenheit').value = "";
}
function Leeg2() {
document.getElementById('Celsius').value = "";
}
<div class="Oefening">
<h1 class="Titel">Oefening 3</h1>
Celsius: <input type="number" id="Celsius" placeholder="°C" onkeyup=Leeg1()> Fahrenheit: <input type="number" id="Fahrenheit" placeholder="°F" onkeyup="Leeg2()"><br />
<input type="button" id="button3" value="Zet om" onclick="Omrekenen(); Vast();" class="Button">
</div>

Here's one way of doing this.
Note that I'm checking for the length of the value from the input. You can't check the truthiness (if (celsius) ...) in this case, since a value of 0 is valid, but would evaluate to false. Checking the length should work for each case.
function Omrekenen() {
var celsius = document.getElementById('Celsius').value;
var fahrenheit = document.getElementById('Fahrenheit').value;
if (celsius.length !== 0) {
document.getElementById('Fahrenheit').value = (celsius * 1.8) + 32;
} else if (fahrenheit.length !== 0) {
document.getElementById('Celsius').value = (fahrenheit / 1.8) - 32;
}
}
function Leeg1() {
document.getElementById('Fahrenheit').value = "";
}
function Leeg2() {
document.getElementById('Celsius').value = "";
}
<div class="Oefening">
<h1 class="Titel">Oefening 3</h1>
Celsius: <input type="number" id="Celsius" placeholder="°C" onkeyup=Leeg1()> Fahrenheit: <input type="number" id="Fahrenheit" placeholder="°F" onkeyup="Leeg2()"><br />
<input type="button" id="button3" value="Zet om" onclick="Omrekenen();" class="Button">
</div>

You can use a state variable also, but you'd also want to handle the paste action in that case.
<script>
var isCalculatingCelsius;
function Omrekenen()
{
var celsius = document.getElementById('Celsius').value;
var fahrenheit = document.getElementById('Fahrenheit').value;
if (isCalculatingCelsius){
document.getElementById('Celsius').value = (fahrenheit / 1.8) - 32;
} else {
document.getElementById('Fahrenheit').value = (celsius * 1.8) + 32;
}
}
function Leeg1(){
isCalculatingCelsius = false;
document.getElementById('Fahrenheit').value = "";
}
function Leeg2(){
isCalculatingCelsius = true;
document.getElementById('Celsius').value = "";
}
</script>
<div class="Oefening">
<h1 class="Titel">Oefening 3</h1>
Celsius: <input type="number" id="Celsius" placeholder="°C" onkeyup="Leeg1()">
Fahrenheit: <input type="number" id="Fahrenheit" placeholder="°F" onkeyup="Leeg2()"><br />
<input type="button" id="button3" value="Zet om" onclick="Omrekenen()" class="Button">
</div>

Related

Using JS to show HTML output of calculation

I am trying to build a calorie calculator using HTML and JS and am currently struggling to show the output on screen (or via console.log). I know I'm doing something very basic quite wrong but can't currently pinpoint what that is.
Here's both my HTML and JS code below:
document.getElementById("bmrForm").addEventListener("submit", calcBMR);
function calcBMR(gender, weightKG, heightCM, age) {
// Calculate BMR
if (gender = 'male') {
let BMR = 10 * weightKG + 6.25 * heightCM - 5 * age + 5;
} else {
let BMR = 10 * weightKG + 6.25 * heightCM - 5 * age - 161;
}
console.log(BMR);
}
<body>
<script src="./script.js"></script>
<section>
<form id="bmrForm" onsubmit="calcBMR()">
<input type="text" id="gender" placeholder="Male or female?">
<input type="number" id="weight" placeholder="Weight in KG">
<input type="number" id="height" placeholder="Height in CM">
<input type="number" id="age" placeholder="How old are you?">
<button type="submit" id="submitBtn">Do Magic!</button>
</form>
<p id="output">0</p>
</section>
</body>
Several things need to be modified in order to achieve your desired result.
The line document.getElementById("bmrForm").addEventListener("submit", calcBMR); is not needed because we can pass in a function directly to the onsubmit attribute of the form element.
The gender, weightKG, heightCM, and age parameters are not automatically passed in to the calcBMR function. The values need to be retrieved from the document.
The BMR variable needs to be defined above the if/else block because of scoping.
A return statement needs to be added to the onsubmit attribute so that the form does not submit and refresh the page. Alternatively, if the desired effect is to update the text on the screen, a button element with a click event handler added to it may be a better option that a form with a submit handler.
Strings are compared using == or === in JavaScript. Therefore, the gender = 'male' part needs to be changed to gender === 'male'.
In order to update the output, the element's textContent can be changed with document.getElementById("output").textContent = BMR.
Below is the code with the changes listed above.
function calcBMR() {
let gender = document.getElementById("gender").value;
let weightKG = document.getElementById("weight").value;
let heightCM = document.getElementById("height").value;
let age = document.getElementById("age").value;
let BMR;
// Calculate BMR
if (gender === 'male') {
BMR = 10 * weightKG + 6.25 * heightCM - 5 * age + 5;
} else {
BMR = 10 * weightKG + 6.25 * heightCM - 5 * age - 161;
}
console.log(BMR);
document.getElementById("output").textContent = BMR;
return false;
}
<body>
<script src="./script.js"></script>
<section>
<form id="bmrForm" onsubmit="return calcBMR()">
<input type="text" id="gender" placeholder="Male or female?">
<input type="number" id="weight" placeholder="Weight in KG">
<input type="number" id="height" placeholder="Height in CM">
<input type="number" id="age" placeholder="How old are you?">
<button type="submit" id="submitBtn">Do Magic!</button>
</form>
<p id="output">0</p>
</section>
First, you are using a button with a type="submit", which is used to submit form data to a resource that will receive it and process it. In this case, you probably just want a button with type="button" that will only do what you've configured it to do (show the results on the screen).
After making that change, you should populate a pre-existing, but empty element with the result.
But you do have an issue with how and where you are declaring BMR. The let declaration should be outside of the if/then code but inside the function so it has scope throughout the function.
Also, your button's id is incorrect in the event handler setup.
Next, any value that you get from an HTML element will be a string and if you intend to do math with that value, you'll need to convert it to a JavaScript number. There are several ways to do this, but one shorthand way is to prepend the value with a + as you'll see I've done below.
Also, if someone were to type Male into the gender textbox, your code would not process it as a male because your code only checks for male, not Male. By forcing the input to lower case, your code will work (provided they spell male correctly). Preferably, you'd use a set of radio buttons or a drop down list for the user to choose from.
And, in conjunction with that, JavaScript uses = for assigning a value, not comparison. For loose equality (automatic type conversion) use == and for strict equality (no type conversion), use ===.
let out = document.getElementById("output");
let gender = document.getElementById("gender");
let height = document.getElementById("height");
let weight = document.getElementById("weight");
let age = document.getElementById("age");
// If you want to pass arguments to the event handler, you need to wrap the handler call in another function
document.getElementById("submitBtn").addEventListener("click", function(){calcBMR(gender.value.toLowerCase(), +weight.value, +height.value, +age.value)});
function calcBMR(gender, weightKG, heightCM, age) {
let BMR = null; // Declare the variable in the function scope
console.log(gender, weightKG, heightCM, age);
// Calculate BMR
if (gender === 'male') {
BMR = 10 * weightKG + 6.25 * heightCM - 5 * age + 5;
} else {
BMR = 10 * weightKG + 6.25 * heightCM - 5 * age - 161;
}
console.log(BMR);
output.textContent = BMR;
}
<body>
<script src="./script.js"></script>
<section>
<form id="bmrForm" onsubmit="calcBMR()">
<input type="text" id="gender" placeholder="Male or female?">
<input type="number" id="weight" placeholder="Weight in KG">
<input type="number" id="height" placeholder="Height in CM">
<input type="number" id="age" placeholder="How old are you?">
<button type="button" id="submitBtn">Do Magic!</button>
</form>
<p id="output">0</p>
</section>
</body>
Working Codepen
There are a few fundamental flaws in your code. Having said that, studying this will really give you a proper understanding of Javascript.
HTML:
<body>
<section>
<form id="bmrForm">
<input type="text" id="gender" placeholder="Male or female?" name="gender">
<input type="number" id="weight" placeholder="Weight in KG" name="weight">
<input type="number" id="height" placeholder="Height in CM" name="height">
<input type="number" id="age" placeholder="How old are you?" name="age">
<button type="submit" id="submitBtn">Do Magic!</button>
</form>
<p id="output">0</p>
</section>
</body>
Javascript:
document.getElementById("bmrForm").addEventListener("submit", calcBMR);
const output = document.querySelector('#output')
function calcBMR(e) {
e.preventDefault();
output.innerText = ''
const formData = new FormData(e.target)
const { age, gender, height, weight} = Object.fromEntries(formData);
let BMR = 0
// Calculate BMR
if (gender === 'male') {
BMR = 10 * parseInt(weight) + 6.25 * parseInt(height) - 5 * parseInt(age) + 5;
} else {
BMR = 10 * parseInt(weight) + 6.25 * parseInt(height) - 5 * parseInt(age) - 161;
}
output.innerText = BMR
}
You can remove the line document.getElementById("bmrForm").addEventListener("submit", calcBMR);
You can pass event to onsubmit - <form id="bmrForm" onsubmit="calcBMR(event)">
function calcBMR(e) {
e.preventDefault();
var elements = document.getElementById("bmrForm").elements; // logic to get all form elements
var obj ={};
for(var i = 0 ; i < elements.length ; i++){
var item = elements.item(i);
obj[item.id] = item.value;
}
const {gender, weight, height, age } = obj; //Get values from obj
// Calculate BMR
let BMR = '';
if (gender === 'male') {
BMR = 10 * weight + 6.25 * height - 5 * age + 5;
} else {
BMR = 10 * weight + 6.25 * height - 5 * age - 161;
}
console.log(BMR);
}
The BMR is in the if tree, it must be in parent.
Try this!
document.getElementById("bmrForm").addEventListener("submit", calcBMR);
const output = document.getElementById('output');
function calcBMR(event) {
// Get the [gender, weightKG, heightCM, age] value
let gender = document.getElementById('gender').value;
let weightKG = document.getElementById('weight').value;
let heightCM = document.getElementById('height').value;
let age = document.getElementById('age').value;
// Set default BMR to 0
let BMR = 0;
// Calculate BMR
if (gender = 'male') {
BMR = 10 * weightKG + 6.25 * heightCM - 5 * age + 5;
} else {
BMR = 10 * weightKG + 6.25 * heightCM - 5 * age - 161;
}
console.log(BMR);
output.innerText = BMR;
// Cancel form submit
event.preventDefault();
return;
}
<body>
<script src="./script.js"></script>
<section>
<form id="bmrForm">
<input type="text" id="gender" placeholder="Male or female?">
<input type="number" id="weight" placeholder="Weight in KG">
<input type="number" id="height" placeholder="Height in CM">
<input type="number" id="age" placeholder="How old are you?">
<button type="submit" id="submitBtn">Do Magic!</button>
</form>
<p id="output">0</p>
</section>
</body>
I used a selector instead of the text field for the gender.
I used form.elements to get the values from the form.
I used event.preventDefault(); to prevent the form from redirecting on submit.
// your form
var form = document.getElementById("formId");
var DoMagic = function(event)
{
event.preventDefault();
var elements = form.elements;
if (elements["gender"].value == "male")
{
var result = 10 * elements["weight"].value + 6.25 * elements["height"].value - 5 * elements["age"].value + 5;
}
else
{
var result = 10 * elements["weight"].value + 6.25 * elements["height"].value - 5 * elements["age"].value - 161;
}
document.getElementById("result").textContent = "Result: " + result;
}
// attach event listener
form.addEventListener("submit", DoMagic, true);
<form id = "formId">
<label>Gender</label>
<select name="gender">
<option value="male">Male</option>
<option value="female">Female</option>
</select>
<br>
<label>Weight (kg)</label>
<input name="weight" type="number">
<br>
<label>Height (cm)</label>
<input name="height" type="number">
<br>
<label>Age (years)</label>
<input name="age" type="number">
<br>
<input type="submit" value="Do Magic!">
</form>
<span id='result'> </span>
Try this one, you are almost done, just by getting value from the input when user clicks the button.
But I have to notice you that submit button will immediately redirect to a new page, you should use click instead if you want to show yourself result.
document.getElementById("submitBtn").addEventListener("click",function(){
let gen = document.querySelector('#gender').value
let weight = document.querySelector('#weight').value
let height = document.querySelector('#height').value
let ages = document.querySelector('#age').value
calcBMR(gen,weight,height,ages)
})
function calcBMR(gender, weightKG, heightCM, age) {
let BMR
// Calculate BMR
if (gender = 'male') {
BMR = 10 * weightKG + 6.25 * heightCM - 5 * age + 5;
} else {
BMR = 10 * weightKG + 6.25 * heightCM - 5 * age - 161;
}
document.querySelector('#output').textContent = BMR;
}
<body>
<script src="./script.js"></script>
<section>
<form id="bmrForm">
<input type="text" id="gender" placeholder="Male or female?">
<input type="number" id="weight" placeholder="Weight in KG">
<input type="number" id="height" placeholder="Height in CM">
<input type="number" id="age" placeholder="How old are you?">
<button id="submitBtn">Do Magic!</button>
</form>
<p id="output">0</p>
</section>
</body>

Use Javascript to Make Calculator

Good Day - I am Learning Javascript, I am trying to create a Calculator to calculate ampere-turn to magnetize a tool (it's related to my job.) I am trying to use some formulas to calculate this ampere-turn. The code seems fine to me, but it's not working. I put some values in the form, and click button submit, but no result found and i don't know why this happens.
I am sharing my code here for your kind review. and help me to fix this problem.
thank you.
function ampereturn()
{
var inputOD = Number(document.ampereturn.inputod.value);
var inputLen = Number(document.ampereturn.inputlen.value);
var InputID = Number(document.ampereturn.Inputid.value);
var InputTurn = Number(document.ampereturn.Inputturn.value);
var ans;
var ldratio = inputLen/inputOD;
var coilradius = InputID/2;
var toolradius = inputOD/2;
var pi = 3.14;
var xcoil = (coilradius * coilradius) * pi;
var xtool = (toolradius * toolradius) * pi;
var factor = xtool/xcoil;
var text = "Use Intermediate Fill-factor formula:";
if(factor >= 0.5)
{
ans = 35000/(ldratio+2)*Inputturn;
document.getElementById('sum').innerHTML = ans;
}
if(factor <= 0.1)
{
ans = 45000/ldratio*Inputturn;
document.getElementById('sum').innerHTML = ans;
}
else
{
document.getElementById('sum').innerHTML = text;
}
}
<form name="ampereturn">
<div class="w3-half w3-margin-top">
<label>Tool OD:</label>
<input id="inputod" class="w3-input w3-border" type="number" placeholder="Input Tool Outer Dia:">
</div>
<div class="w3-half w3-margin-top">
<label>Tool Lenght:</label>
<input id="inputlen" class="w3-input w3-border" type="number" placeholder="Input Tool Length">
</div>
<div class="w3-half w3-margin-top">
<label>Coil ID:</label>
<input id="Inputid" class="w3-input w3-border" type="number" placeholder="Input Coil Internal Dia:">
</div>
<div class="w3-half w3-margin-top">
<label>Coil Turn:</label>
<input id="Inputturn" class="w3-input w3-border" type="number" placeholder="Input Number of turn in coil:">
</div>
<div class="w3-half w3-margin-top">
<label>Required Ampere:</label>
<p id="sum"></p>
</div>
<button type="button" onclick="ampereturn()">Submit</button>
</form>
<br><hr>
thank you in advance. ....
Change the function name which is same as the form name.
Change Inputturn to InputTurn in the if condition.
Required Code:
function Ampereturn()
{
var inputOD = Number(document.ampereturn.inputod.value);
var inputLen = Number(document.ampereturn.inputlen.value);
var InputID = Number(document.ampereturn.Inputid.value);
var InputTurn = Number(document.ampereturn.Inputturn.value);
var ans;
var ldratio = inputLen/inputOD;
var coilradius = InputID/2;
var toolradius = inputOD/2;
var pi = 3.14;
var xcoil = (coilradius * coilradius) * pi;
var xtool = (toolradius * toolradius) * pi;
var factor = xtool/xcoil;
var text = "Use Intermediate Fill-factor formula:";
if(factor >= 0.5)
{
ans = 35000/(ldratio+2)*InputTurn;
document.getElementById('sum').innerHTML = ans;
}
else if(factor <=0.1)
{
ans = 45000/ldratio*InputTurn;
document.getElementById('sum').innerHTML = ans;
}
else
{
document.getElementById('sum').innerHTML = text;
}
}

Why does this function's results show up as NaN?

I have this simple piece of code:
var numb1 = document.getElementById("numb1")
var numb2 = document.getElementById("numb2")
var numb3 = document.getElementById("numb3")
var numb4 = document.getElementById("numb4")
var v1 = parseInt(numb1)
var v2 = parseInt(numb2)
var v3 = parseInt(numb3)
var v4 = parseInt(numb4)
var t = parseInt(0)
function myFunction() {
if (numb1.checked == true) {
var t = v1 + t
} else if (numb2.checked == true) {
var t = v2 + t
} else if (numb3.checked == true) {
var t = v3 + t
} else if (numb4.checked == true) {
var t = v4 + t
}
document.getElementById("demo").innerHTML = t
}
<input id="numb1" type="radio" value="10">
<input id="numb2" type="radio" value="50">
<input id="numb3" type="radio" value="80">
<input id="numb4" type="radio" value="120">
<button type="button" onclick="myFunction()">Submit</button>
<p id="demo"></p>
I get that I definitely could have been more efficient when making my variables, but my problem is that even after I use parseInt() to go from string to integer, the end result in demo displays NaN. Is there something wrong with the way I defined the variables, or is it the calculation of the end value?
Because parseInt( elementObject ) doesn't return a valid number.
You wanted to parse the value, with a radix
var v1 = parseInt(numb1.value, 10);
And you have to get those values inside the function, when the value has actually changed.
Also, add some semicolons, they aren't always needed, but it's good practice to add them, and don't redeclare variables
var numb1 = document.getElementById("numb1");
var numb2 = document.getElementById("numb2");
var numb3 = document.getElementById("numb3");
var numb4 = document.getElementById("numb4");
function myFunction() {
var v1 = parseInt(numb1.value, 10);
var v2 = parseInt(numb2.value, 10);
var v3 = parseInt(numb3.value, 10);
var v4 = parseInt(numb4.value, 10);
var t = 0;
if (numb1.checked) {
t = v1 + t;
} else if (numb2.checked) {
t = v2 + t;
} else if (numb3.checked) {
t = v3 + t;
} else if (numb4.checked) {
t = v4 + t;
}
document.getElementById("demo").innerHTML = t
}
<input id="numb1" type="radio" value="10">
<input id="numb2" type="radio" value="50">
<input id="numb3" type="radio" value="80">
<input id="numb4" type="radio" value="120">
<button type="button" onclick="myFunction()">Submit</button>
<p id="demo"></p>
I agree with the answer by adeneo. The issue is that you are parseInting an HTML Input Element.
And you already got the answer.
But I noticed that you use if..else
So, You want only one value to be selected by the user.
So, There is a short method which also help to improve the loading speed and reduce lines of codes.
using forms
function myFunction(){
t=parseInt(document.forms[0]["num"].value);
document.getElementById("demo").innerHTML=t
}
<form>
<input id="numb1" name="num" type="radio" value="10">
<input id="numb2" name="num" type="radio" value="50">
<input id="numb3" name="num" type="radio" value="80">
<input id="numb4" name="num" type="radio" value="120">
<button type="button" onclick="myFunction()">Submit</button>
</form>
<p id="demo"></p>

Javascript won't calculate

Can anyone point me in the right direction as to why my calculate button will not calculate. It doesn't even throw any of the error messages up to the screen, but my clear button does work. It's probably something small, but I cannot figure it out for the life of me -_-.
var $ = function(id) {
return document.getElementById(id);
}
var virusRemovalPrice = 20.00;
var websiteMakingCost = 75.00;
var computerServicingCost = 100.00;
var calculateTotal = function() {
var virusRemoval = parseFloat($("virusRemoval").value);
var websiteMaking = parseFloat($("websiteMaking").value);
var computerOptimizationAndSetUp = parseFloat($("computerOptimizationAndSetUp").value);
var totalCost = parseFloat(($("totalCost").value));
if (isNaN(virusRemoval) || virusRemoval < 0) {
alert("Value must be numeric and at least zero. ");
$("virusRemoval").focus()
} else if (isNaN(websiteMaking) || websiteMaking < 0) {
alert("Value must be numeric and at least zero. ");
$("websiteMaking").focus()
} else if (isNaN(computerOptimizationAndSetUp) || computerOptimizationAndSetUp < 0) {
alert("Value must be numeric and at least zero. ");
$("computerOptimizationAndSetUp").focus()
} else {
do {
var ii = 0;
var cost = ((virusRemovalPrice * virusRemoval) + (websiteMakingCost * websiteMaking) + (computerServicingCost * computerOptimizationAndSetUp));
$("cost").value = cost.toFixed(2); //total cost final
if (cost > 1) {
alert("Your total is " + cost + " hope to see you soon!");
}
} while (ii = 0)
}
};
var clearValues = function() {
var virusRemoval = parseFloat($("virusRemoval").value = "");
var websiteMaking = parseFloat($("websiteMaking").value = "");
var computerOptimizationAndSetUp = parseFloat($("computerOptimizationAndSetUp").value = "");
var totalCost = parseFloat($("totalCost").value = "");
}
<form class="anotheremoved">
<h2>Total Cost</h2>
<label for="virusRemoval">Virus Removal:</label>
<br />
<input type="text" id="virusRemoval">
<br />
<label for="websiteMaking">Website Design:</label>
<br />
<input type="text" id="websiteMaking">
<br />
<label for="computerOptimizationAndSetUp">Computer Setup:</label>
<br />
<input type="text" id="computerOptimizationAndSetUp">
<br />
<br />
<label for="totalCost">Your Total Cost is:</label>
<input type="text" id="TotalCost" disabled>
<br />
<input class="removed" type="button" id="calculateTotal" value="Calculate " onblur="calculateTotal()">
<input class="removed" type="button" id="clear" value="Clear" onclick="clearValues()">
</form>
The reason why the loop is in there is because we were required to have a loop and I couldn't find a good reason to have one, so I used one that would always be true to get it out of the way lol. Probably will throw an infinate loop at me or something, but I'll figure that out later, I'm just trying to get the dang on thing to do something here haha. I've tried to rewrite this 2 other times and still get to the same spot, so I realize it's probably something small, and I am new to Javascript. Thank you.
The problem is that you have id="calculateTotal" in the input button. Element IDs are automatically turned into top-level variables, so this is replacing the function named calculateTotal. Simply give the function a different name from the button's ID.
You also have a typo. The ID of the Total Cost field is TotalCost, but the code uses $('totalCost') and $('cost').
It's also better to do the calculation in onclick, not onblur. Otherwise you have to click on the button and then click on something else to see the result.
In the clearValues function, there's no need to assign variables and call parseFloat. Just set each of the values to the empty string. You could also just use <input type="reset">, that resets all the inputs in the form to their initial values automatically.
var $ = function(id) {
return document.getElementById(id);
}
var virusRemovalPrice = 20.00;
var websiteMakingCost = 75.00;
var computerServicingCost = 100.00;
var calculateTotal = function() {
var virusRemoval = parseFloat($("virusRemoval").value);
var websiteMaking = parseFloat($("websiteMaking").value);
var computerOptimizationAndSetUp = parseFloat($("computerOptimizationAndSetUp").value);
var totalCost = parseFloat(($("TotalCost").value));
if (isNaN(virusRemoval) || virusRemoval < 0) {
alert("Value must be numeric and at least zero. ");
$("virusRemoval").focus()
} else if (isNaN(websiteMaking) || websiteMaking < 0) {
alert("Value must be numeric and at least zero. ");
$("websiteMaking").focus()
} else if (isNaN(computerOptimizationAndSetUp) || computerOptimizationAndSetUp < 0) {
alert("Value must be numeric and at least zero. ");
$("computerOptimizationAndSetUp").focus()
} else {
do {
var ii = 0;
var cost = ((virusRemovalPrice * virusRemoval) + (websiteMakingCost * websiteMaking) + (computerServicingCost * computerOptimizationAndSetUp));
$("TotalCost").value = cost.toFixed(2); //total cost final
if (cost > 1) {
alert("Your total is " + cost + " hope to see you soon!");
}
} while (ii = 0)
}
};
var clearValues = function() {
$("virusRemoval").value = "";
$("websiteMaking").value = "";
$("computerOptimizationAndSetUp").value = "";
$("TotalCost").value = "";
}
<form class="anotheremoved">
<h2>Total Cost</h2>
<label for="virusRemoval">Virus Removal:</label>
<br />
<input type="text" id="virusRemoval">
<br />
<label for="websiteMaking">Website Design:</label>
<br />
<input type="text" id="websiteMaking">
<br />
<label for="computerOptimizationAndSetUp">Computer Setup:</label>
<br />
<input type="text" id="computerOptimizationAndSetUp">
<br />
<br />
<label for="totalCost">Your Total Cost is:</label>
<input type="text" id="TotalCost" disabled>
<br />
<input class="removed" type="button" id="calculateTotalButton" value="Calculate " onclick="calculateTotal()">
<input class="removed" type="button" id="clear" value="Clear" onclick="clearValues()">
</form>

JavaScript html forms calculator not working

im trying to make a simple perimeter calculator for a projector screen.
The code should take the response from a radio button input and the diagonal length to calculate the perimeter accordingly.
here is my code atm:
<html>
<body>
<script language="javascript">
function calc() {
var form = document.forms.Calculator;
var A = Number(getSelectedValue(form.elements.A));
var B = Number(getSelectedValue(form.elements.B));
if (A = 0) {
L = 0.8;
H = 0.6;
} else if (A = 1) {
L = 0.872;
H = 0.49;
} else {
L = 0.922;
H = 0.386;
}
form.elements.Total.value = 2 * B * (L + H);
}
function getSelectedValue(flds) {
var i = 0;
var len = flds.length;
while (i < len) {
if (flds[i].checked) {
return flds[i].value;
}
i++;
}
return "";
}
</script>
<title>Calculator</title> <pre>
<form name="Calculator">
<label>A</label>
4:3: <input name="A" type="radio" onChange="calc()" value="0" checked>
16:9: <input name="A" type="radio" onChange="calc()" value="1">
2.39:1: <input name="A" type="radio" onChange="calc()" value="2">
<label>B</label>
Screen Size: <input name="B" type="text" onChange="calc()" checked>
<label>Total</label>
<input type="text" name="Total" onChange="calc()" readonly size="10"><br>
<input type="submit" value="Submit Calculation"> <input type="reset" value="Clear">
</form>
</pre>
</body>
</html>
Your function getSelectedValue is wrong. It loops trough an array of elements to see which one is checked. You are trying to do the same for B which is only one element so that is not going trough the loop and thus returns ''.
So instead of
var B = Number(getSelectedValue(form.elements.B));
try
var B = Number(form.elements.B.value);
Also, your if else statements are wrong. It should be == instead of =:
if (A == 0) {
L = 0.8;
H = 0.6;
} else if (A == 1) {
L = 0.872;
H = 0.49;
} else {
L = 0.922;
H = 0.386;
}

Categories

Resources