Don't calculate if a field is empty (Js calculator) - javascript

I'm trying to limit a calculation only when a field is blank. I have many other fields that are calculated simultaneously, I would like to limit the calculation to only the fields that have not been filled.
I don't know JS very well, so I hope to be able to find help here ... Thanks for any answers, I leave more info below.
Basically everything works fine. However, when the bodyfat field is empty, the calculation for BMR and TDEE Katch McArdle and Cunningham Formula is performed.
What I am trying to do is to calculate the McArdle and Cunningham Formula fields only when the Bodyfat field contains values.
calculate = function()
{
var weight = document.getElementById('weight').value;
var height = document.getElementById('height').value;
var age = document.getElementById('age').value;
var bodyfat = document.getElementById('bodyfat').value / 100;
var select_lvl = document.querySelector('#a_level option:checked').value;
//Sex Selection Hide-Show Div//
var sex = document.querySelector('input[name="radios"]:checked').value;
document.getElementById('bmr-sexuomo').hidden = sex !== 'Male';
document.getElementById('bmr-sexdonna').hidden = sex !== 'Female';
document.getElementById('MifflinMale').hidden = sex !== 'Male';
document.getElementById('MifflinFemale').hidden = sex !== 'Female';
var bmr_mifflin_man = (10*weight) + (6.25*height) - (5*age) + 5;
document.getElementById('bmr_mifflin_man').value = bmr_mifflin_man.toLocaleString('it-IT', {maximumFractionDigits: 0}) + " Kcal";
var tdee_mifflin_man = (bmr_mifflin_man*select_lvl);
document.getElementById('tdee_mifflin_man').value = tdee_mifflin_man.toLocaleString('it-IT', {maximumFractionDigits: 0}) + " Kcal";
var bmr_mifflin_woman = (10*weight) + (6.25*height) - (5*age) - 161;
document.getElementById('bmr_mifflin_woman').value = bmr_mifflin_woman.toLocaleString('it-IT', {maximumFractionDigits: 0}) + " Kcal";
var tdee_mifflin_woman = (bmr_mifflin_woman*select_lvl);
document.getElementById('tdee_mifflin_woman').value = tdee_mifflin_woman.toLocaleString('it-IT', {maximumFractionDigits: 0}) + " Kcal";
//Result BMR Katch Mc Ardle Formula
var bmr_katch = (370 + ( 21.6 * ( weight * ( 1 - bodyfat ))));
document.getElementById('bmr_katch').value = bmr_katch.toLocaleString('it-IT', {maximumFractionDigits: 0}) + " Kcal";
//Result TDEE Katch Mc Ardle Formula
var tdee_katch = (bmr_katch*select_lvl);
document.getElementById('tdee_katch').value = bmr_katch.toLocaleString('it-IT', {maximumFractionDigits: 0}) + " Kcal";
//Result BMR Cunningham Formula
var bmr_cunningham = (500 + ( 22 * ( weight * ( 1 - bodyfat ))));
document.getElementById('bmr_cunningham').value = bmr_cunningham.toLocaleString('it-IT', {maximumFractionDigits: 0}) + " Kcal";
//Result TDEE Cunningham Formula
var tdee_cunningham = (bmr_cunningham*select_lvl);
document.getElementById('tdee_cunningham').value = bmr_cunningham.toLocaleString('it-IT', {maximumFractionDigits: 0}) + " Kcal";
//This is Activity Level Radio Selection//
var leggeros = document.getElementById('leggeros').value * 1.2;
var attivos = document.getElementById('attivos').value * 1.375;
var allenatos = document.getElementById('allenatos').value * 1.55;
var Mattivos = document.getElementById('Mattivos').value * 1.75;
var Eattivos = document.getElementById('Eattivos').value * 1.9;
}
//Reset Function
function resetFields() {
document.getElementById("bmrcalc").reset();
document.getElementById('bmr_katch').value = ''
document.getElementById('bmr_mifflin_man').value = ''
var ele = document.getElementsByName("radiosa");
for(var i=0;i<ele.length;i++)
ele[i].checked = false;
}
https://jsfiddle.net/snake93/4n9dgbfw/3/

I have added a if condition for checking body fat Now it will works fine.
calculate = function()
{
var weight = document.getElementById('weight').value || 0;
var height = document.getElementById('height').value || 0;
var age = document.getElementById('age').value || 0;
var bodyfat = document.getElementById('bodyfat').value / 100;
var select_lvl = document.querySelector('#a_level option:checked').value;
//Sex Selection Hide-Show Div//
var sex = document.querySelector('input[name="radios"]:checked').value || "Male" ;
document.getElementById('bmr-sexuomo').hidden = sex !== 'Male';
document.getElementById('bmr-sexdonna').hidden = sex !== 'Female';
document.getElementById('MifflinMale').hidden = sex !== 'Male';
document.getElementById('MifflinFemale').hidden = sex !== 'Female';
if(bodyfat!=""){
var bmr_mifflin_man = (10*weight) + (6.25*height) - (5*age) + 5;
document.getElementById('bmr_mifflin_man').value = bmr_mifflin_man.toLocaleString('it-IT', {maximumFractionDigits: 0}) + " Kcal";
var tdee_mifflin_man = (bmr_mifflin_man*select_lvl);
document.getElementById('tdee_mifflin_man').value = tdee_mifflin_man.toLocaleString('it-IT', {maximumFractionDigits: 0}) + " Kcal";
var bmr_mifflin_woman = (10*weight) + (6.25*height) - (5*age) - 161;
document.getElementById('bmr_mifflin_woman').value = bmr_mifflin_woman.toLocaleString('it-IT', {maximumFractionDigits: 0}) + " Kcal";
var tdee_mifflin_woman = (bmr_mifflin_woman*select_lvl);
document.getElementById('tdee_mifflin_woman').value = tdee_mifflin_woman.toLocaleString('it-IT', {maximumFractionDigits: 0}) + " Kcal";
//Result BMR Katch Mc Ardle Formula
var bmr_katch = (370 + ( 21.6 * ( weight * ( 1 - bodyfat ))));
document.getElementById('bmr_katch').value = bmr_katch.toLocaleString('it-IT', {maximumFractionDigits: 0}) + " Kcal";
//Result TDEE Katch Mc Ardle Formula
var tdee_katch = (bmr_katch*select_lvl);
document.getElementById('tdee_katch').value = bmr_katch.toLocaleString('it-IT', {maximumFractionDigits: 0}) + " Kcal";
//Result BMR Cunningham Formula
var bmr_cunningham = (500 + ( 22 * ( weight * ( 1 - bodyfat ))));
document.getElementById('bmr_cunningham').value = bmr_cunningham.toLocaleString('it-IT', {maximumFractionDigits: 0}) + " Kcal";
//Result TDEE Cunningham Formula
var tdee_cunningham = (bmr_cunningham*select_lvl);
document.getElementById('tdee_cunningham').value = bmr_cunningham.toLocaleString('it-IT', {maximumFractionDigits: 0}) + " Kcal";
}
//This is Activity Level Radio Selection//
var leggeros = document.getElementById('leggeros').value * 1.2;
var attivos = document.getElementById('attivos').value * 1.375;
var allenatos = document.getElementById('allenatos').value * 1.55;
var Mattivos = document.getElementById('Mattivos').value * 1.75;
var Eattivos = document.getElementById('Eattivos').value * 1.9;
}
//Reset Function
function resetFields() {
document.getElementById("bmrcalc").reset();
document.getElementById('bmr_katch').value = ''
document.getElementById('bmr_mifflin_man').value = ''
var ele = document.getElementsByName("radiosa");
for(var i=0;i<ele.length;i++)
ele[i].checked = false;
}
.mts-field {
width:100%;
text-align: right;
border-bottom: 2px solid #DCDCDE !important;
background: #fff;
}
<label id="prov" class="mts-label">Peso</label>
<input oninput="javascript: if (this.value.length > this.maxLength) this.value = this.value.slice(0, this.maxLength);" type="number" class="mts-field" maxlength="3" id="weight" name="weight1" placeholder="es: 70Kg" form="bmrcalc" required/>
<label class="mts-label">Altezza</label>
<input oninput="javascript: if (this.value.length > this.maxLength) this.value = this.value.slice(0, this.maxLength);" type="number" class="mts-field" maxlength="3" id="height" name="height1" placeholder="es: 170cm" form="bmrcalc" required/>
<label class="mts-label">Età</label>
<input oninput="javascript: if (this.value.length > this.maxLength) this.value = this.value.slice(0, this.maxLength);" type="number" class="mts-field" maxlength="2" id="age" name="age1" placeholder="es: 25 anni" form="bmrcalc" required/>
<label class="mts-label">Bodyfat in %</label>
<input oninput="javascript: if (this.value.length > this.maxLength) this.value = this.value.slice(0, this.maxLength);" type="number" class="mts-field" maxlength="2" id="bodyfat" name"bodyfat1" placeholder="es: 15%" form="bmrcalc" />
<div class="mts-label">Sesso</div>
<!--Radio Button Sex-->
<div class="mts-radio-button">
<input type="radio" id="sexuomo" name="radios" value="Male" form="bmrcalc" required>
<label class="mts-label-radio" for="sexuomo">Uomo</label>
</div>
<div class="mts-radio-button1">
<input type="radio" id="sexdonna" name="radios" value="Female" form="bmrcalc" required>
<label class="mts-label-radio" for="sexdonna">Donna</label>
</div>
<!--Select Activity Level-->
<div class="container_level">
<select class="a_level" id="a_level" name="activ_level">
<option value="0">Stile di vita / Attività fisica</option>
<option id="leggeros" name="radiosa" value="1.2">Sedentario (1.2)</option>
<option id="attivos" name="radiosa" value="1.375">Leggero (1.375) </option>
<option id="allenatos" name="radiosa" value="1.55">Moderato (1.55)</option>
<option id="Mattivos" name="radiosa" value="1.75">Attivo (1.75)</option>
<option id="Eattivos" name="radiosa" value="1.9">Estremamente attivo (1.9)</option>
</select>
</div>
<!---BMR Mifflin StJeor Result Field--->
<br>
<label class="mts-label">BMR Mifflin St Jeor Formula</label><br>
<div id="bmr-sexuomo">
<label class="mts-label">Male</label><br>
<input type="text" class="mts-field" id="bmr_mifflin_man" name="bmr_mifflin_man"
placeholder="0.000,0 Kcal" min="1" readonly/>
</div>
<br>
<div id="bmr-sexdonna" hidden>
<label class="mts-label">Female</label><br>
<input type="text" class="mts-field" id="bmr_mifflin_woman" name="bmr_mifflin_woman"
placeholder="0.000,0 Kcal" min="1" readonly/>
</div>
<!---TDEE Mifflin StJeor Result Field--->
<br>
<label class="mts-label">TDEE Mifflin St Jeor Formula</label><br>
<div id="MifflinMale">
<label class="mts-label">Male</label><br>
<input type="text" class="mts-field" id="tdee_mifflin_man" name="tdee_mifflin_man"
placeholder="0.000,0 Kcal Uomo" min="1" readonly/>
</div>
<br>
<div id="MifflinFemale" hidden>
<label class="mts-label">Female</label><br>
<input type="text" class="mts-field" id="tdee_mifflin_woman" name="tdee_mifflin_woman"
placeholder="0.000,0 Kcal donna" min="1" readonly/>
</div>
<!---BMR Katch McArdle Formula--->
<br>
<label class="mts-label">BMR Katch McArdle Formula</label>
<div id="Ktch">
<input type="text" class="mts-field" id="bmr_katch" name="bmr_katch"
placeholder="0.000,0 Kcal" maxlength="6" readonly/>
</div>
<!---TDEE Katch McArdle Formula--->
<br>
<label class="mts-label">TDEE Katch McArdle Formula</label>
<div id="Ktch1">
<input type="text" class="mts-field" id="tdee_katch" name="tdee_katch"
placeholder="0.000,0 Kcal" maxlength="6" readonly/>
</div>
<!---BMR Cunningham Formula--->
<br>
<label class="mts-label">BMR Cunningham Formula</label>
<div id="Cunningham">
<input type="text" class="mts-field" id="bmr_cunningham" name="bmr_cunningham"
placeholder="0.000,0 Kcal" maxlength="6" readonly/>
</div>
<!---TDEE Cunningham Formula--->
<br>
<label class="mts-label">TDEE Cunningham Formula</label>
<div id="Cunninghams">
<input type="text" class="mts-field" id="tdee_cunningham" name="tdee_cunningham"
placeholder="0.000,0 Kcal" maxlength="6" readonly/>
</div>
<!---Calc & Reset Button--->
<br>
<form action="" id="bmrcalc">
</form>
<button name="calculate" onclick="calculate()">Calculate</button>
<button id="reset" onclick="resetFields()">Reset</button>

You need to reverse engineer it (think opposite of what you want). For example, think that calling a function when there is something in the textbox is the same as not calling a function when there isn't something in the textbox. So now you have your answer! You just need to add this in your code:
if (document.getElementById('bodyfat').value==""){
preventDefault();
alert("You need to enter something in the textbox first");
}
Thinking like this can help save a lot of time. You didn't need to know anything about Javascript for this, right?

Related

Making button enabled when javascript return true

I'm trying to do a form with a basic captcha. Currently, because I'm a novice HTML coder, I only did the submit button enabled when the user clicks the verify button (it doesn'T enable itself when it sees return true.) And I'm trying to make it so if it returns return true i want to make the button enabled, and disabled at other times. Here is the link to the code: https://codepen.io/pen/GRpVmve
I would appreciate if anyone helps.
remove button verify button and add to input oninput function
function Check(){
document.getElementById("button2").disabled = true;
if(ValidCaptcha()){
document.getElementById("button2").disabled = false;
}
}
function Captcha(){
var alpha = new Array('a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z');
var i;
for (i=0;i<6;i++){
var a = alpha[Math.floor(Math.random() * alpha.length)];
var b = alpha[Math.floor(Math.random() * alpha.length)];
var c = alpha[Math.floor(Math.random() * alpha.length)];
var d = alpha[Math.floor(Math.random() * alpha.length)];
var e = alpha[Math.floor(Math.random() * alpha.length)];
var f = alpha[Math.floor(Math.random() * alpha.length)];
var g = alpha[Math.floor(Math.random() * alpha.length)];
}
var code = a + ' ' + b + ' ' + ' ' + c + ' ' + d + ' ' + e + ' '+ f + ' ' + g;
document.getElementById("mainCaptcha").value = code;
Check()
}
function ValidCaptcha(){
var string1 = removeSpaces(document.getElementById('mainCaptcha').value);
var string2 = removeSpaces(document.getElementById('txtInput').value);
if (string1 == string2){
return true;
}
else{
return false;
}
}
function removeSpaces(string){
return string.split(' ').join('');
}
<form action="https://www.w3schools.com/action_page.php">
<label for="fname">First name:</label><br>
<input type="text" id="fname" name="fname" value="John"><br>
<label for="lname">Last name:</label><br>
<input type="text" id="lname" name="lname" value="Doe"><br><br>
<h3>Gender</h3>
<input type="radio" id="male" name="gender" value="male">
<label for="male">Male</label><br>
<input type="radio" id="female" name="gender" value="female">
<label for="female">Female</label><br>
<input type="radio" id="other" name="gender" value="other">
<label for="other">Other</label>
<body onload="Captcha();">
<table>
<tr>
<h3>
Captcha<br />
</td>
</tr>
<tr>
<td>
<input type="text" id="mainCaptcha" disabled/>
<input type="button" id="refresh" value="Refresh" onclick="Captcha();" />
</td>
</tr>
<tr>
<td>
<input type="text"oninput="Check()" name="captcha" id="txtInput"/>
</td>
</tr>
<tr>
<td>
<input type="submit" id="button2" value="Send" disabled>
</td>
</tr>
</table>
</body>
</form>
I think this will work for you...
window.onload=()=>{
document.getElementById('button2').disabled = true;
let text = document.getElementById('txtInput').value;
Captcha();
}
function Captcha(){
var alpha = new Array('a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z');
for (i=0;i<6;i++){
var a = alpha[Math.floor(Math.random() * alpha.length)];
var b = alpha[Math.floor(Math.random() * alpha.length)];
var c = alpha[Math.floor(Math.random() * alpha.length)];
var d = alpha[Math.floor(Math.random() * alpha.length)];
var e = alpha[Math.floor(Math.random() * alpha.length)];
var f = alpha[Math.floor(Math.random() * alpha.length)];
var g = alpha[Math.floor(Math.random() * alpha.length)];
}
var code = a + ' ' + b + ' ' + ' ' + c + ' ' + d + ' ' + e + ' '+ f + ' ' + g;
document.getElementById("mainCaptcha").value = code
}
function ValidCaptcha(){
var string1 = removeSpaces(document.getElementById('mainCaptcha').value);
var string2 = removeSpaces(document.getElementById('txtInput').value);
if (string1 == string2){
document.getElementById('button2').disabled = false;
}
else{
document.getElementById('button2').disabled = true;
}
}
function removeSpaces(string){
return string.split(' ').join('');
}
function check(x){
if(x.length<7 || x.length>7){
document.getElementById('button2').disabled = true;
}
}
<form action="https://www.w3schools.com/action_page.php">
<label for="fname">First name:</label><br>
<input type="text" id="fname" name="fname" value="John"><br>
<label for="lname">Last name:</label><br>
<input type="text" id="lname" name="lname" value="Doe"><br><br>
<h3>Gender</h3>
<input type="radio" id="male" name="gender" value="male">
<label for="male">Male</label><br>
<input type="radio" id="female" name="gender" value="female">
<label for="female">Female</label><br>
<input type="radio" id="other" name="gender" value="other">
<label for="other">Other</label>
<body onload="Captcha();">
<table>
<tr>
<h3>
Captcha<br />
</td>
</tr>
<tr>
<td>
<input type="text" id="mainCaptcha" disabled/>
<input type="button" id="refresh" value="Refresh" onclick="Captcha();" />
</td>
</tr>
<tr>
<td>
<input type="text" id="txtInput" onkeyup="check(this.value)"/>
</td>
</tr>
<tr>
<td>
<input id="button1" type="button" value="Verify" onclick="ValidCaptcha()">
<input type="submit" id="button2" value="Send">
</td>
</tr>
</table>
</body>
</form>

calculation of packing charges in java script

I have an tax invoice page for making invoice. I am using javascript for calculating the amount. I want to add courier charges in javascript. Can anybody help me?
Here is code
function calculateTotal() {
var totalAmount = 0;
$("[id^='price_']").each(function() {
var id = $(this).attr('id');
id = id.replace("price_", '');
var price = $('#price_' + id).val();
var quantity = $('#quantity_' + id).val();
if (!quantity) {
quantity = 1;
}
var total = price * quantity;
$('#total_' + id).val(parseFloat(total));
totalAmount += total;
});
$('#subTotal').val(parseFloat(totalAmount));
var taxRate = $("#taxRate").val();
var subTotal = $('#subTotal').val();
if (subTotal) {
var taxAmount = subTotal * taxRate / 100;
$('#taxAmount').val(taxAmount);
subTotal = parseFloat(subTotal) + parseFloat(taxAmount);
$('#totalAftertax').val(subTotal);
var amountPaid = $('#amountPaid').val();
var totalAftertax = $('#totalAftertax').val();
if (amountPaid && totalAftertax) {
totalAftertax = totalAftertax - amountPaid;
$('#amountDue').val(totalAftertax);
} else {
$('#amountDue').val(subTotal);
}
}
CSS is only for demo ( you can ignore it )
I added packaging fees & shipping fees with also FREE option each
$(document).ready(function() {
calculateTotal();
});
function calculateTotal() {
var totalAmount = 0;
$("[id^='price_']").each(function() {
var id = $(this).attr('id').replace("price_", '');
var price = $('#price_' + id).val();
var quantity = $('#quantity_' + id).val();
if (!quantity) {
quantity = 1;
}
var total = price * quantity;
$('#total_' + id).val(parseFloat(total));
totalAmount += total;
});
$('#subTotal').val(parseFloat(totalAmount));
var taxRate = parseFloat($("#taxRate").val());
var subTotal = parseFloat($('#subTotal').val());
if (subTotal) {
var taxAmount = subTotal * taxRate / 100;
$('#taxAmount').val(taxAmount);
subTotal = parseFloat(subTotal) + parseFloat(taxAmount);
$('#totalAftertax').val(subTotal);
var amountPaid = $('#amountPaid').val();
var totalAftertax = $('#totalAftertax').val();
if (amountPaid && totalAftertax) {
totalAftertax = totalAftertax - amountPaid;
$('#amountDue').val(totalAftertax);
} else {
$('#amountDue').val(subTotal);
}
var amoutDue = parseFloat($('#amountDue').val());
var shipping = parseFloat($('#shipping').val());
var packaging = parseFloat($('#packaging').val());
$('#amountDue').val(amoutDue + shipping + packaging);
}
}
[disabled],
[readonly] {
background-color: #eee;
border: 1px solid #ccc;
color: #888;
}
div {
padding: 5px 10px;
}
div:nth-child(even) {
background: #eee;
}
label {
display: inline-block;
width: 120px;
}
<div>
<input id="price_1" type="number" value="5" />
<input id="quantity_1" type="number" value="3" min="1" />
<input id="total_1" type="number" value="15" readonly />
</div>
<div>
<input id="price_3" type="number" value="15" />
<input id="quantity_3" type="number" value="1" min="1" />
<input id="total_3" type="number" value="15" readonly />
</div>
<div>
<input id="price_8" type="number" value="20" />
<input id="quantity_8" type="number" value="2" min="1" />
<input id="total_8" type="number" value="40" readonly />
</div>
<div align="center">
<button type="button" onclick="calculateTotal()">Update Cart</button>
</div>
<hr />
<div><label>Sub Total:</label>
<input id="subTotal" type="number" value="0" readonly /></div>
<div><label>Tax Rate:</label>
<input id="taxRate" type="number" value="15" readonly /></div>
<div><label>Tax Amount:</label>
<input id="taxAmount" type="number" value="0" readonly /></div>
<div><label>Total After Tax:</label>
<input id="totalAftertax" type="number" value="0" readonly /></div>
<div>
<label>Shipping:</label>
<select id="shipping" onchange="calculateTotal()">
<option value="0">Regular FREE ( 12-15 days )</option>
<option value="12.99">Express $12.99 ( 1-2 days )</option>
<option value="9.99">UPS $9.99 ( 2-3 days )</option>
<option value="6.99">DHL $6.99 ( 3-5 days )</option>
</select>
</div>
<div>
<label>Packaging:</label>
<select id="packaging" onchange="calculateTotal()">
<option value="0">Regular FREE</option>
<option value="2.99">Package 1 $2.99</option>
<option value="4.99">Package 2 $4.99</option>
<option value="7.99">Package 3 $7.99</option>
</select>
</div>
<div><label>Amount Paid:</label> <input id="amountPaid" type="number" value="15" readonly /></div>
<div><label>Amount Due:</label> <input id="amountDue" type="number" value="0" readonly /></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Why does form not reset (all fields and div of result) after click clear?

I want display div id="showResult" after click calculate button and clear all input and div id="showResult" after click clear button in a form. But clear button doesn't work after I click the button.
What's the problem? How can I solve this problem?
window.onload = function BMR() {
var gender = document.getElementById('gender');
var weight = document.getElementById('weight');
var height = document.getElementById('height');
var age = document.getElementById('age');
var calculate = document.getElementById('calculate');
calculate.addEventListener('click', toBmr);
function toBmr() {
var select = null;
if (gender.value && weight.value && height.value && age.value) {
if (document.getElementById('gender').checked) {
select = document.getElementById('gender').value;
}
if (select == 'male') {
var result = (10 * weight.value) + (6.25 * height.value) - (5 * age.value) + 5;
document.getElementById('result').innerHTML = Number(result).toFixed(2);
} else {
var result = (10 * weight.value) + (6.25 * height.value) - (5 * age.value) - 161;
document.getElementById('result').innerHTML = Number(result).toFixed(2);
}
document.getElementById('showResult').style.display = "block";
} else {
result = " ";
}
};
};
function clearForm() {
document.getElementById("do-form").reset();
}
<form name="do-form" id="do-form">
<p>BMR Calculator</p>
<p>Gender:
<input type="radio" id="gender" name="gender" value="male" checked="checked">Male
<input type="radio" id="gender" name="gender" value="female">Female
</p>
<p>Weight: <input type="number" name="weight" id="weight" size="10" maxlength="6" onkeypress="if(this.value.length > 5) return false;"> kg</p>
<p>Height: <input type="number" name="height" id="height" size="10" maxlength="6" onkeypress="if(this.value.length > 5) return false;"> cm</p>
<p>Age: <input type="number" name="age" id="age" size="10" maxlength="3" onkeypress="if(this.value.length > 2) return false;"></p>
<button type="button" id="calculate">Calculate</button>
<button type="button" id="clear" onclick="clearForm()">Clear</button><br><br>
<div class="row-result-tab" id="showResult" style="display:none;">
<label>BMR = <span id="result"></span> calories/day</label>
</div>
</form>
You needed to hide the div in the clearForm
Here is your code cleaned up based on the DRY principle (don't repeat yourself)
We could get rid of some testing if we could trust the browser to respect the type="number" which is fairly well supported
window.addEventListener("load", () => {
document.getElementById('calculate').addEventListener('click', toBmr);
});
const toBmr = () => {
const gender = document.querySelector('[name=gender]:checked').value;
// the "number" fields will not allow other data than numbers
let weight = +document.getElementById('weight').value;
let height = +document.getElementById('height').value;
let age = +document.getElementById('age').value;
if (weight && age && height) {
let result = (10 * weight) + (6.25 * height) - (5 * age)
result += gender === 'male' ? 5 : -161; // add 5 for male, subtract 161 if female
document.getElementById('result').innerHTML = result.toFixed(2);
document.getElementById('showResult').style.display = "block";
}
};
const clearForm = () => {
document.getElementById("do-form").reset();
document.getElementById('showResult').style.display = "none";
}
<form name="do-form" id="do-form">
<p>BMR Calculator</p>
<p>Gender:
<input type="radio" name="gender" value="male" checked="checked">Male
<input type="radio" name="gender" value="female">Female
</p>
<p>Weight: <input type="number" name="weight" id="weight" size="10" maxlength="6" onkeypress="if(this.value.length > 5) return false;"> kg</p>
<p>Height: <input type="number" name="height" id="height" size="10" maxlength="6" onkeypress="if(this.value.length > 5) return false;"> cm</p>
<p>Age: <input type="number" name="age" id="age" size="10" maxlength="3" onkeypress="if(this.value.length > 2) return false;"></p>
<button type="button" id="calculate">Calculate</button>
<button type="button" id="clear" onclick="clearForm()">Clear</button><br><br>
<div class="row-result-tab" id="showResult" style="display:none;">
<label>BMR = <span id="result"></span> calories/day</label>
</div>
</form>
The result div can not auto hide, you need add code to hide it
document.getElementById('showResult').style.visibility = "hidden";
or
document.getElementById('showResult').style.display= "none";
window.onload = function BMR() {
var gender = document.getElementById('gender');
var weight = document.getElementById('weight');
var height = document.getElementById('height');
var age = document.getElementById('age');
var calculate = document.getElementById('calculate');
calculate.addEventListener('click', toBmr);
function toBmr() {
var select = null;
if (gender.value && weight.value && height.value && age.value) {
if (document.getElementById('gender').checked) {
select = document.getElementById('gender').value;
}
if (select == 'male') {
var result = (10 * weight.value) + (6.25 * height.value) - (5 * age.value) + 5;
document.getElementById('result').innerHTML = Number(result).toFixed(2);
} else {
var result = (10 * weight.value) + (6.25 * height.value) - (5 * age.value) - 161;
document.getElementById('result').innerHTML = Number(result).toFixed(2);
}
document.getElementById('showResult').style.display = "block";
} else {
result = " ";
}
};
};
function clearForm() {
document.getElementById("do-form").reset();
//document.getElementById('showResult').style.visibility = "hidden";
document.getElementById('showResult').style.display = "none";
}
<form name="do-form" id="do-form">
<p>BMR Calculator</p>
<p>Gender:
<input type="radio" id="gender" name="gender" value="male" checked="checked">Male
<input type="radio" id="gender" name="gender" value="female">Female
</p>
<p>Weight: <input type="number" name="weight" id="weight" size="10" maxlength="6" onkeypress="if(this.value.length > 5) return false;"> kg</p>
<p>Height: <input type="number" name="height" id="height" size="10" maxlength="6" onkeypress="if(this.value.length > 5) return false;"> cm</p>
<p>Age: <input type="number" name="age" id="age" size="10" maxlength="3" onkeypress="if(this.value.length > 2) return false;"></p>
<button type="button" id="calculate">Calculate</button>
<button type="button" id="clear" onclick="clearForm()">Clear</button><br><br>
<div class="row-result-tab" id="showResult" style="display:none;">
<label>BMR = <span id="result"></span> calories/day</label>
</div>
</form>
I took some time to improve your code. As given in other answers already. You need to set the display of your result html back to none.
window.onload = function BMR() {
// Init
var gender = document.getElementById('gender');
var weight = document.getElementById('weight');
var height = document.getElementById('height');
var age = document.getElementById('age');
var calculate = document.getElementById('calculate');
// Click handler
calculate.addEventListener('click', toBmr);
function toBmr() {
// Init
// Very good practice to first declare your vars
// However include result as well here
// Remove select because it's not doing anything
var result = "";
var penalty = 0;
if (gender.value && weight.value && height.value && age.value && gender.checked) {
// When you have duplicate code, check the difference!
// Only the penalty given at the end is different!
if (gender.value == 'male') {
penalty = 5;
} else {
penalty = -161;
}
// Now we calculate with one formula
result = (10 * weight.value) + (6.25 * height.value) - (5 * age.value) + penalty;
// Add to html
document.getElementById('result').innerHTML = Number(result).toFixed(2);
document.getElementById('showResult').style.display = "block";
}
};
};
function clearForm() {
// This resets the form fields
document.getElementById("do-form").reset();
// This remove result again
document.getElementById('showResult').style.display = "none";
}
<form name="do-form" id="do-form">
<p>BMR Calculator</p>
<p>Gender:
<input type="radio" id="gender" name="gender" value="male" checked="checked">Male
<input type="radio" id="gender" name="gender" value="female">Female
</p>
<p>Weight: <input type="number" name="weight" id="weight" size="10" maxlength="6" onkeypress="if(this.value.length > 5) return false;"> kg</p>
<p>Height: <input type="number" name="height" id="height" size="10" maxlength="6" onkeypress="if(this.value.length > 5) return false;"> cm</p>
<p>Age: <input type="number" name="age" id="age" size="10" maxlength="3" onkeypress="if(this.value.length > 2) return false;"></p>
<button type="button" id="calculate">Calculate</button>
<button type="button" id="clear" onclick="clearForm()">Clear</button><br><br>
<div class="row-result-tab" id="showResult" style="display:none;">
<label>BMR = <span id="result"></span> calories/day</label>
</div>
</form>

Show total savings in discount calculate

Trying to get the total saving amount to display in field id saving
Here what I've so far from Stackoverflow
getPrice = function() {
var numVal1 = Number(document.getElementById("price").value);
var numVal2 = Number(document.getElementById("discount").value) / 100;
var totalValue = numVal1 - (numVal1 * numVal2)
document.getElementById("total").value = totalValue.toFixed(2);
}
<input id="price" placeholder="Amount">
<br>
<input id="discount" placeholder="Discount %">
<br>
<button onclick="getPrice()">Get total</button>
<br>
<input id="saving" placeholder="Total Savings">
<br>
<input readonly id="total" placeholder="Discounted Price">
<br>
As simple as that :
getPrice = function() {
var numVal1 = Number(document.getElementById("price").value);
var numVal2 = Number(document.getElementById("discount").value) / 100;
var totalValue = numVal1 - (numVal1 * numVal2)
var savingValue = numVal1 - totalValue;
document.getElementById("saving").value = savingValue.toFixed(2);
document.getElementById("total").value = totalValue.toFixed(2);
}
<input id="price" placeholder="Amount">
<br>
<input id="discount" placeholder="Discount %">
<br>
<button onclick="getPrice()">Get total</button>
<br>
<input id="saving" placeholder="Total Savings">
<br>
<input readonly id="total" placeholder="Discounted Price">
<br>

limit digits in var multiplication total

I have this:
var ivu = (total3);
document.getElementById("project_pay_total_field4").value = "$" + total3 * 0.07 ;
The multiplication produces this:
$10.080000000000002
--Its too long and when done in regular calculator it only says 10.08; how can i fix that?
Here is the function:
<script type = "text/javascript">
function project_pay_detail() {
var rate = document.getElementById("project_rate_field").value;
var time = document.getElementById("project_time_field").value;
var total1 = (rate * time);
document.getElementById("project_pay_total_field").value = "$" + total1 + ".00";
var rate = document.getElementById("project_rate_field2").value;
var time = document.getElementById("project_time_field2").value;
var total2 = (rate * time);
document.getElementById("project_pay_total_field2").value = "$" + total2 + ".00";
var total3 = (total1 + total2);
document.getElementById("project_pay_total_field3").value = "$" + total3 + ".00" ;
var ivu = (total3);
document.getElementById("project_pay_total_field4").value = "$" + total3 * 0.07 ;
}
</script>
Heres is the form
<div id="project_pay">Pay Rate<input type="text" name="project_rate_field" id="project_rate_field" class="field" value="" /></div>
<div id="project_pay">Total Hours<input type="text" name="project_time_field" id="project_time_field" class="field" value="" /></div>
<div id="project_pay">Project Total<input type="text" name="project_pay_total_field" id="project_pay_total_field" class="field" readonly="readonly" value="" /></div>
<input name="project_pay_details_calculate" type="button" value="Calculate1" onClick="project_pay_detail()" /></input>
<br>
<div id="project_pay">Pay Rate2<input type="text" name="project_rate_field2" id="project_rate_field2" class="field" value="" /></div>
<div id="project_pay">Total Hours2<input type="text" name="project_time_field2" id="project_time_field2" class="field" value="" /></div>
<div id="project_pay">Project Total2<input type="text" name="project_pay_total_field2" id="project_pay_total_field2" class="field" title="0.00" readonly="readonly" value="" /></div>
<input name="project_pay_details_refresh" type="button" value="Calculate2" onClick="project_pay_detail()" /></input>
<div id="project_pay">Total<input type="text" name="project_pay_total_field3" id="project_pay_total_field3" class="field" title="0.00" readonly="readonly" value="" /></div>
<div id="project_pay">Ivu<input type="text" name="project_pay_total_field4" id="project_pay_total_field4" class="field" title="0.00" readonly="readonly" value="" /></div>
</div>
try using: number.toFixed(x)
var result = (total3 * 0.07);
document.getElementById("project_pay_total_field4").value = "$" + result.toFixed(2);
http://www.w3schools.com/jsref/jsref_tofixed.asp
total3 = Math.round(total3 * 100) / 100;

Categories

Resources