calculate fourth value automatically - javascript

EDIT2: I removed the input validations, so now values don't get corrupted.
Added more functions to onkeyup method. However, if for eg, I enter three values, for Widht, GSM and Weight, Length will be calculated but since all functions are in on key up, along with length, other values change as well.
How do I make it so that when Length is being calculated, other values don't alter?
EDIT: For eg, if value for Length, Width and GSM is provided, then value for Weight will be assigned { formula: Length * Width * GSM/3100 }
if value for Width, GSM and Weight are given, then Length should be calculated { formula: (Weight * 3100) / width * GSM }
and so on.
I have four input boxes, What I want is when the user puts in any of the three boxes the fourth value should generate automatically in the fourth box.
Right now my code works when there is a fixed box in which we have to get the fourth value
New HTML:
<!DOCTYPE html>
<html>
<head>
<title>Paper Calc 2</title>
<script type="text/javascript" src = "js/test.js"></script>
<link rel="stylesheet" type="text/css" href="css/CALC.css">
<meta charset="utf-8">
</head>
<body>
<div class="container-fluid">
<div id = "case_one" class="calcoptions sizemod">
<h5>1. To find the weight (in <b>Kilograms</b>) of a ream containing 500 sheets of a given size in <b>inches</b> and <b>Gram-Weight.</b></h5>
<br>
<div class="row">
<div class="col-md-6">
Length: <input type="number" step="0.01" name="length_in" id="length" placeholder="Length(inch)" onkeyup="fun(); fun2(); fun3();">inch
<br><br>
Width: <input type="number" step="0.01" name="width_in" id="width" placeholder="Width(inch)" onkeyup="fun(); fun2(); fun4();">inch
<br><br>
GSM: <span class="extraSpace"> </span><input type="number" step="0.01" name="length_in" id="GSM" placeholder="GSM" onkeyup="fun(); fun3(); fun4();"> <!-- <button type = "button" name = "calc2" class = 'btnclass' id="cal2" onclick="func2()"> calc2-->
</button>
<br><br>
Weight: <input type="number" step = "0.01" name="Weight_Kg" id = "weight" onkeyup="fun2(); fun3(); fun4();"> <!-- KG <button type = "button" name = "calc1" id="cal1" class = 'btnclass' onclick="func1()">
calc1 -->
</button>
<br><br>
</div>
<p id='err'></p>
</body>
</html>
New JS:
function fun()
{
var l = document.getElementById('length').value;
var w = document.getElementById('width').value;
var g = document.getElementById('GSM').value;
if (l && w && g)
{
var wt = document.getElementById('weight');
var calculate = (eval(l)*eval(w)*eval(g))/3100;
wt.value = calculate.toFixed(2);
}
};
function fun2()
{
var l = document.getElementById('length').value;
var w = document.getElementById('width').value;
var wt = document.getElementById('weight').value;
if (l && w && wt)
{
var g = document.getElementById('GSM');
var calculate = (eval(wt)*3100)/(eval(l)*eval(w));
g.value = calculate.toFixed(2);
}
};
function fun3()
{
var l = document.getElementById('length').value;
var wt = document.getElementById('weight').value;
var g = document.getElementById('GSM').value;
if (l && g && wt)
{
var w = document.getElementById('width');
var calculate = (eval(wt)*3100)/(eval(l)*eval(g));
w.value = calculate.toFixed(2);
}
};
function fun4()
{
var w = document.getElementById('width').value;
var wt = document.getElementById('weight').value;
var g = document.getElementById('GSM').value;
if (w && g && wt)
{
var l = document.getElementById('length');
var calculate = (eval(wt)*3100)/(eval(w)*eval(g));
l.value = calculate.toFixed(2);
}
};
function calculateWeightInInches() {
var Length = document.getElementById("txt_weight").value;
var width = document.getElementById("txt_width").value;
var GSM = document.getElementById("txt_GSM").value;
var calculate = (Length * width * GSM) / 3100;
var result = document.getElementById("txt_Result");
// if (Length < 0)
// {
// document.getElementById('err').innerHTML = 'Incorrect Length!';
// }
error = document.getElementById('err_1');
if (calculate < 0 || width > 300 || width < 1 || GSM < 5 || GSM > 800 || Length < 1 || Length > 99) {
result.value = 0;
error.style.display = 'block';
} else {
result.value = calculate.toFixed(2);
error.style.display = 'none';
}
}
<div class="container-fluid">
<div id="case_one" class="calcoptions sizemod">
<h5>1. To find the weight (in <b>Kilograms</b>) of a ream containing 500 sheets of a given size in <b>inches</b> and <b>Gram-Weight.</b></h5>
<br>
<div class="row">
<div class="col-md-6">
Length: <input type="number" step="0.01" name="length_in" id="txt_weight" placeholder="Length(inch)" min="1" max="99" onkeyup="calculateWeightInInches();">inch
<br><br> Width: <input type="number" step="0.01" name="width_in" id="txt_width" placeholder="Width(inch)" min="1" max='300' onkeyup="calculateWeightInInches();">inch
<br><br> GSM: <span class="extraSpace"> </span><input type="number" min="5" max="800" step="0.01" name="length_in" id="txt_GSM" placeholder="GSM" onkeyup="calculateWeightInInches();">
<br><br> Weight: <input type="number" step="0.01" name="Weight_Kg" id="txt_Result" readonly="readonly">KG
<br><br>
</div>
<div class="col-md-6">
<p id="err_1" style="display: none;">
Valid Range: <br> L = 1 to 99 inch <br> W = 1 to 99 inch <br> GSM = 5 to 800 <br><br> Formula: (Length * width * GSM) / 3100
</p>
</div>
</div>
</div>
<div id="case_two" class="calcoptions sizemod">
I am trying by putting another function in onkeyup but it ruins the code.
[because values keep changing]
Any help would be appreciated!

function calculateWeightInInches() {
var Length = document.getElementById("txt_weight").value;
var width = document.getElementById("txt_width").value;
var GSM = document.getElementById("txt_GSM").value;
var calculate = (Length * width * GSM) / 3100;
var result = document.getElementById("txt_Result");
// if (Length < 0)
// {
// document.getElementById('err').innerHTML = 'Incorrect Length!';
// }
error = document.getElementById('err_1');
if(calculate < 0 || width > 300 || width < 1 || GSM < 5 || GSM > 800 || Length < 1 || Length > 99)
{
result.value = 0;
error.style.display = 'block';
}
else
{
if(Length && width && GSM) {
var GSMElement = document.getElementById("txt_GSM");
var lengthElement = document.getElementById("txt_weight");
var widthElement = document.getElementById("txt_width");
var elementsArray = [GSMElement,widthElement,lengthElement]
elementsArray.forEach(function(ele){
ele.addEventListener('change', function() {
result.value = calculate.toFixed(2);
error.style.display = 'none';
})
})
}
}
}

Related

How do I add the error message for BMI calculator fields next/under them instead of on the top of the page?

So I'm trying to get the error message to go next to the field, but I have no idea what I'm doing, I'm pretty new at this, sorry to bother you guys.
Here's the whole code:
function computeBMI() {
var height = 0;
var weight = 0;
height = Number(document.getElementById("height").value);
weight = Number(document.getElementById("weight").value);
if (height == 0 | height > 220) {
document.getElementById('errorMsg').innerHTML = "Use Appropriate Height";
return 0;
}
if (weight == 0 | weight < 20) {
document.getElementById('errorMsg').innerHTML = "Use Appropriate Weight";
return 0;
}
var BMI = weight / (height / 100 * height / 100);
document.getElementById("output").innerText = Math.round(BMI * 100) / 100;
var output = Math.round(BMI * 100) / 100;
if (output < 18.5)
document.getElementById("comment").innerText = "Underweight";
else if (output >= 18.5 && output <= 25)
document.getElementById("comment").innerText = "Normal";
else if (output > 25)
document.getElementById("comment").innerText = "Overweight";
}
<html>
<head>
<title>BMI Calculator</title>
</head>
<body>
<div id="errorMsg"></div>
<h1>Body Mass Index Calculator</h1>
<p>Enter your height: <input type="text" id="height" /></p> <span id="errorMsg"><
<p>Enter your weight: <input type="text" id="weight"/></p>
<input type="submit" value="computeBMI" onclick="computeBMI();">
<h1>Your BMI is: <span id="output">?</span></h1>
<h2>This means you are: <span id="comment"> ?</span> </h2>
</body>
To do it your way you would need a separate error message area next to each input, and each one would need a unique ID - currently you have two elements whose ID is "errorMsg", one of which is in the wrong place in the layout. An ID must (by definition) uniquely identify an element, so clearly that isn't going to work. When you refer to "errorMsg" in your code, JavaScript will just pick the first one it finds and assume you meant that one. It has no way of telling them apart.
But anyway for the validation you're trying to do, you don't actually need to write your own code at all. If you put your fields inside a form, and handle the submit event of the form, you can then use HTML5 validation rules on the fields themselves to restrict the allowed input.
Here's a demo:
Note the addEventListener to handle the "submit" event of the form and run some Javascript.
Note also the <form> and </form> tags round the fields and button, and lastly the type="number", required, min and max attributes on the input fields themselves.
var form = document.getElementById("BMIForm");
form.addEventListener("submit", function(event) {
event.preventDefault(); //stop a postback
computeBMI();
});
function computeBMI() {
var height = 0;
var weight = 0;
height = Number(document.getElementById("height").value);
weight = Number(document.getElementById("weight").value);
var BMI = weight / (height / 100 * height / 100);
document.getElementById("output").innerText = Math.round(BMI * 100) / 100;
var output = Math.round(BMI * 100) / 100;
if (output < 18.5)
document.getElementById("comment").innerText = "Underweight";
else if (output >= 18.5 && output <= 25)
document.getElementById("comment").innerText = "Normal";
else if (output > 25)
document.getElementById("comment").innerText = "Overweight";
}
<html>
<head>
<title>BMI Calculator</title>
</head>
<body>
<h1>Body Mass Index Calculator</h1>
<form id="BMIForm">
<p>Enter your height: <input type="number" required min="0" max="220" id="height" /></p>
<p>Enter your weight: <input type="number" required min="0" max="20" id="weight"/></p>
<input type="submit" value="computeBMI">
</form>
<h1>Your BMI is: <span id="output">?</span></h1>
<h2>This means you are: <span id="comment"> ?</span> </h2>
</body>
You can learn more about HTML form validation here: https://developer.mozilla.org/en-US/docs/Learn/Forms/Form_validation
You tried to use an element's ID, but you can only select one element using ID. You have to use class, and then select which element in the satisfying list of elements contain the class you want.
Also, I updated your code a little bit so instead of validating if the answer fits in an anti-category, it checks if it does not fit in a specified category.
function computeBMI() {
document.getElementsByClassName('errorMsg')[0].innerHTML = ""
document.getElementsByClassName('errorMsg')[1].innerHTML = ""
var height = parseInt(document.getElementById("height").value);
var weight = parseInt(document.getElementById("weight").value);
var returnVal = false
if (!(height > 0 && height <= 220)) {
document.getElementsByClassName('errorMsg')[0].innerHTML = "Use Appropriate Height";
returnVal = returnVal || true
}
if (!(weight > 0 && weight < 20)) {
document.getElementsByClassName('errorMsg')[1].innerHTML = "Use Appropriate Weight";
returnVal = returnVal || true
}
if (returnVal) {
return 0
}
var BMI = weight / (height / 100 * height / 100);
document.getElementById("output").innerText = Math.round(BMI * 100) / 100;
var output = Math.round(BMI * 100) / 100;
if (output < 18.5)
document.getElementById("comment").innerText = "Underweight";
else if (output >= 18.5 && output <= 25)
document.getElementById("comment").innerText = "Normal";
else if (output > 25)
document.getElementById("comment").innerText = "Overweight";
}
<html>
<head>
<title>BMI Calculator</title>
</head>
<body>
<h1>Body Mass Index Calculator</h1>
Enter your height:
<input type="text" id="height" placeholder="height" />
<span class="errorMsg"></span><br> Enter your weight:
<input type="text" id="weight" placeholder="weight" />
<span class="errorMsg"></span><br>
<input type="submit" value="computeBMI" onclick="computeBMI();">
<h1>Your BMI is: <span id="output">?</span></h1>
<h2>This means you are: <span id="comment"> ?</span> </h2>
</body>

Coloring with a two color scale in HTML and JavaScript

I have an input element whose value is a number between 0 and 100. I am attempting to style the element via a two-color scale, taking its value as the input.
I am planning on making a simple gradient:
When the number is 100, the element's background color is green #00ff00
When the number is 0, it is red #ff0000
When the number is 50, it displays a yellow color #ffff00
The in-between values should be colored according to the scale.
I have tried using an if statement in JavaScript, but that fails to create a gradient, as there is a hard border between red, yellow, and green (sans gradient). See the code below:
var x = 0;
function color() {
x = document.getElementById("color").value;
console.log(x);
if (x > 50) {
document.getElementById('color').style.backgroundColor = "#00ff00";
}
else if (x == 50) {
document.getElementById('color').style.backgroundColor = "#ffff00";
}
else {
document.getElementById('color').style.backgroundColor = "#ff0000";
}
}
<button onclick="color();">Run</button>
<input type="number" id='color' value=50></input>
<!-- The input is not disabled for value debugging. -->
Is there concise way to perform this task?
const updateColor = (target) => {
const value = target.value;
//#00ff00 100
//#ffff00 50
//#ff0000 0
const R = Math.round((255 / 50) * (value < 50 ? 50 : 100 - value)).toString(16)
const G = Math.round((255 / 50) * (value > 50 ? 50 : value)).toString(16)
const twoDigit = (d) => ("0" + d).slice(-2);
const nextColor = '#' + twoDigit(R) + twoDigit(G) + '00';
target.style.background = nextColor
}
document.getElementById('color').addEventListener('change', (e) => updateColor(e.target));
document.addEventListener("DOMContentLoaded", function (event) {
updateColor(document.getElementById('color'))
});
<html>
<body>
<input type="number" id="color" min="0" max="100" value="0">
</body>
</html>
You can use Html Range input for this purpose and Use javascript for getting its value. Like:
<input id="myId" type="range" min="0" max="100">
Use Javascript to get its value by using its ID. Use a Javascript function. Either call it using a button or add onchange event.
You are just missing a style property...
just do this
document.getElementById("color").style.background = "Any Color";
or if you want to change text color then
document.getElementById("color").style.color = "Any Color";
Here I wrote full code for your problem:-
<input type="number" id="color" min="0" max="100" onkeyup="check()">
<script>
function check(){
c = document.getElementById("color");
x = c.value;
if(x==0)
c.style.background="Red";
else if(x==50)
c.style.background = "Yellow";
else
c.style.background = "Green";
}
</script>
I have found the optimal way to create a 2 color scale that uses vibrant, hexadecimal colors:
var colval = 0;
var R = 0;
var G = 0;
var B = 0;
function check() {
c = document.getElementById("color");
x = c.value;
if (x > 50) {
R = Math.round(-0.051 * x ** 2 + 2.55 * x + 255);
G = 255;
} else if (x < 50) {
R = 255;
G = Math.round(-0.051 * x ** 2 + 7.65 * x + 0);
} else {
R = 255;
G = 255;
}
B = 0;
colval = "#" + R.toString(16) + G.toString(16) + "00";
c.style.background = colval;
}
<html>
<body>
<input type="number" id="color" min="0" max="100" value="0" onkeyup="check()">
</body>
</html>

Why my InnerHTML code won't display any data in the form fields?

I made a simple change calculator. After playing with the code, I managed to make it calculate the values I needed but I can't make it populate my form. If I use alert, the function is right but if I try to use innerHTML to fill the fields, nothing happens. I am really stuck on this one. :(
var quarters;
var dimes;
var nickels;
var pennies;
function Calculate() {
if (cents >= 25) {
quarters = Math.floor(cents / 25);
var qreminder = cents % 25;
if (qreminder <= 24) {
dimes = Math.floor(qreminder / 10);
var dreminder = qreminder % 10;
}
if (dreminder < 10) {
nickels = Math.floor(dreminder / 5);
var nreminder = dreminder % 5;
}
if (nreminder < 5) {
pennies = nreminder / 1;
}
document.getElementById("quarters").innerHTML = quarters;
document.getElementById("dimes").innerHTML = dimes;
document.getElementById("nickels").innerHTML = nickels;
document.getElementById("pennies").innerHTML = pennies;
}
if (cents < 25) {
quarters = Math.floor(cents / 25);
var qreminder = cents % 25;
if (qreminder <= 24) {
dimes = Math.floor(qreminder / 10);
var dreminder = qreminder % 10;
}
if (dreminder < 10) {
nickels = Math.floor(dreminder / 5);
var nreminder = dreminder % 5;
}
if (nreminder < 5) {
pennies = nreminder / 1;
}
document.getElementById("quarters").innerHTML = quarters;
document.getElementById("dimes").innerHTML = dimes;
document.getElementById("nickels").innerHTML = nickels;
document.getElementById("pennies").innerHTML = pennies;
}
}
var cents = document.getElementById("cents").value;
document.getElementById("calculate").addEventListener("click", Calculate);
<div id="content">
<h1>Change Calculator</h1>
<label>Enter number of cents (0-99):</label>
<input type="text" id="cents" />
<input type="button" value="Calculate" name="calculate" id="calculate" /><br />
<p> </p>
<label>Quarters:</label>
<input type="text" id="quarters" class="disabled" disabled="disabled" /><br />
<label>Dimes:</label>
<input type="text" id="dimes" class="disabled" disabled="disabled" /><br />
<label>Nickels:</label>
<input type="text" id="nickels" class="disabled" disabled="disabled" /><br />
<label>Pennies:</label>
<input type="text" id="pennies" class="disabled" disabled="disabled" /><br />
<p> </p>
Setting the .innerHTML property of <input> types will not do anything. Instead, set the .value property of those elements.
document.getElementById("quarters").value = quarters;
document.getElementById("dimes").value = dimes;
document.getElementById("nickels").value = nickels;
document.getElementById("pennies").value = pennies;

Auto substract both values from 100

I created two input fields where they should substract from each other keeping a max value at 100.
Currently it substracted value is shown in the second value. I want it to be interchangeable. Irrespective of whether I put in first or second input field, the answer shows in the other.
Could someone help?
function updateDue() {
var total = parseInt(document.getElementById("totalval").value);
var val2 = parseInt(document.getElementById("inideposit").value);
// to make sure that they are numbers
if (!total) { total = 0; }
if (!val2) { val2 = 0; }
var ansD = document.getElementById("remainingval");
ansD.value = total - val2;
var val1 = parseInt(document.getElementById("inideposit").value);
// to make sure that they are numbers
if (!total) { total = 0; }
if (!val1) { val1 = 0; }
var ansD = document.getElementById("remainingval");
ansD.value = total - val1;
}
<input type="hidden" id="totalval" name="totalval" value="100" onchange="updateDue()">
<div>
Enter Value:
<input type="text" name="inideposit" class="form-control" id="inideposit" onchange="updateDue()">
</div>
<div>
Substracted:
<input type="text" name="remainingval" class="form-control" id="remainingval" onchange="updateDue()">
</div>
The simple way to achieve this would be to group the inputs by class and attach a single event handler to them. Then you can take the entered value from 100, and set the result to the field which was not interacted with by the user. To do that in jQuery is trivial:
$('.updatedue').on('input', function() {
var total = parseInt($('#totalval').val(), 10) || 0;
var subtracted = total - (parseInt(this.value, 10) || 0);
$('.updatedue').not(this).val(subtracted);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="hidden" id="totalval" name="totalval" value="100" />
<div>
Enter Value:
<input type="text" name="inideposit" class="updatedue form-control" id="inideposit" />
</div>
<div>
Subtracted:
<input type="text" name="remainingval" class="updatedue form-control" id="remainingval" />
</div>
You can easily validate this so that outputs < 0 and > 100 can be discounted, if required.
Edit your code as below
function updateDue(box) {
var total = parseInt(document.getElementById("totalval").value);
if(box == 1){
var val = parseInt(document.getElementById("inideposit").value);
// to make sure that they are numbers
if (!total) { total = 0; }
if (!val) { val = 0; }
var ansD = document.getElementById("remainingval");
ansD.value = total - val;
}else if(box == 2){
var val = parseInt(document.getElementById("remainingval").value);
// to make sure that they are numbers
if (!total) { total = 0; }
if (!val) { val = 0; }
var ansD = document.getElementById("inideposit");
ansD.value = total - val;
}
}
<input type="hidden" id="totalval" name="totalval" value="100" onchange="updateDue(0)">
<div>
Enter Value:
<input type="text" name="inideposit" class="form-control" id="inideposit" onchange="updateDue(1)">
</div>
<div>
Substracted:
<input type="text" name="remainingval" class="form-control" id="remainingval" onchange="updateDue(2)">
</div>

Javascript: Get Typeerror - element is null

I have a BMI calculator in Wordpress, that get's the
Typeerror:
result is null and
health is null
The calculator works fine in fiddle https://jsfiddle.net/2au9y34x/2/
but don't on Wordpress. I have placed the script in the footer, so that the HTML is read first, so that is not where the problem is.
Can anyone help solve this problem?
Javascript is:
<script type='text/javascript'>
var form = document.querySelector('form[name=bmi]');
var onSubmit = function(event) {
event.preventDefault();
var healthMessage;
var result = form.querySelector('.result');
var health = form.querySelector('.health');
var weight = parseInt(form.querySelector('input[name=weight]').value, 10);
var height = parseInt(form.querySelector('input[name=height]').value, 10);
var bmi = (weight / (height / 100 * height / 100)).toFixed(1);
if (bmi < 18.5) {
healthMessage = 'undervægtig';
} else if (bmi > 18.5 && bmi < 25) {
healthMessage = 'normal vægtig';
} else if (bmi > 25) {
healthMessage = 'overvægtig';
}
result.innerHTML = bmi;
health.innerHTML = healthMessage;
}
form.addEventListener('submit', onSubmit, false);
</script>
HTML is:
<form name="bmi">
<h1>Mål dit BMI:</h1>
<label>
<input type="text" name="weight" id="weight" placeholder="Vægt (kg)">
<input type="text" name="height" id="height" placeholder="Højde (cm)">
<input type="submit" name="submit" id="submit" value="Udregn BMI">
</label>
<div class="calculation">
<div>
Dit BMI er: <span class="result"></span>
</div>
<div>
Dette betyder at du er: <span class="health"></span>
</div>
</div>
</form>
Add the javascript after the closing tag of form
OR you can try this
window.onload = function() {
var form = document.querySelector('form[name=bmi]');
var onSubmit = function(event) {
event.preventDefault();
var healthMessage;
var result = form.querySelector('.result');
var health = form.querySelector('.health');
var weight = parseInt(form.querySelector('input[name=weight]').value, 10);
var height = parseInt(form.querySelector('input[name=height]').value, 10);
var bmi = (weight / (height / 100 * height / 100)).toFixed(1);
if (bmi < 18.5) {
healthMessage = 'undervægtig';
} else if (bmi > 18.5 && bmi < 25) {
healthMessage = 'normal vægtig';
} else if (bmi > 25) {
healthMessage = 'overvægtig';
}
result.innerHTML = bmi;
health.innerHTML = healthMessage;
}
form.addEventListener('submit', onSubmit, false);
}

Categories