I made a calculator with JavaScript for calculate result automatically. It's work but I can't remove decimal.
Here is my code:
$(document).ready(function() {
$(".input").keyup(function() {
var val1 = +$(".value1").val();
var val2 = +$(".value2").val();
var val3 = +$(".value3").val();
var val4 = +$(".value4").val();
var val5 = (".result");
var decval5 = (val5);
$(decval5).val(((((val1 / 8) + val2) / 16) + val3) * val4);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<div style="border: 1px solid #D3D3D3;background:#fff;">
<div style="padding:10px 0px 10px 10px;">
<div style="font-size:20px;"></div>
<br>
<center>
input1
<input type="text" class="input value3">input2
<input type="text" class="input value2"> input3
<input type="text" class="input value1"> input4
<input type="text" class="input value4"> = result
<input type="text" disabled="disabled" class="result">
</center>
</div>
<br>
</div>
You can use Math.round():
$(document).ready(function() {
$(".input").keyup(function() {
var val1 = +$(".value1").val();
var val2 = +$(".value2").val();
var val3 = +$(".value3").val();
var val4 = +$(".value4").val();
var val5 = (".result");
var decval5 = (val5);
$(decval5).val(Math.round(((((val1 / 8) + val2) / 16) + val3) * val4));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div style="border: 1px solid #D3D3D3;background:#fff;">
<div style="padding:10px 0px 10px 10px;">
<div style="font-size:20px;"></div>
<br>
<center>
input1
<input type="text" class="input value3">input2
<input type="text" class="input value2"> input3
<input type="text" class="input value1"> input4
<input type="text" class="input value4"> = result
<input type="text" disabled="disabled" class="result">
</center>
</div>
<br>
</div>
try,
$(decval5).val(Math.round(((((val1 / 8) + val2) / 16) + val3) * val4));
You can round the answer up or down or just truncate it:
$(document).ready(function() {
$(".input").keyup(function() {
var val1 = +$(".value1").val();
var val2 = +$(".value2").val();
var val3 = +$(".value3").val();
var val4 = +$(".value4").val();
var val5 = (".result");
var decval5 = (val5);
$(decval5).val(((((val1 / 8) + val2) / 16) + val3) * val4);
// Round Up:
console.log(Math.ceil(parseFloat($(decval5).val())));
// Round Down:
console.log(Math.floor(parseFloat($(decval5).val())));
// Truncate:
console.log(parseFloat($(decval5).val()).toFixed(0));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<div style="border: 1px solid #D3D3D3;background:#fff;">
<div style="padding:10px 0px 10px 10px;">
<div style="font-size:20px;"></div>
<br>
<center>
input1
<input type="text" class="input value3">input2
<input type="text" class="input value2"> input3
<input type="text" class="input value1"> input4
<input type="text" class="input value4"> = result
<input type="text" disabled="disabled" class="result">
</center>
</div>
<br>
</div>
Related
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?
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>
I'm trying to work out the percentage value for each field in a form. However my current code is only working out the value for the first field or whichever one is focused.
I'd like it so that the percentage value only for the filed in the same fieldset
The current code works but i'd like to apply to to multiple fieldsets without them interfering with other inputs on the same page
In the snippet you can see that the two separate amounts which are editing each others details
function percentageCal() {
var $price = $(".form-item--invamt .form-item__input").on("input", calculatePerc),
$percentage = $(".form-item__input-expand .percentage").on("input", calculatePrice),
$currency = $(".form-item__input-expand .currency").on("focus", removePercent),
$none = $(".form-item--charges .no-charge").on("focus", removePercent),
$increase = $(".wrapper-types__percentage-value"),
$increaseWrap = $(".wrapper-types__percentage");
$($percentage).add($currency).keypress(function(event) {
if (event.which != 8 && event.which != 0 && (event.which < 48 || event.which > 57)) {
return false;
}
});
function calculatePrice() {
var percentage = parseFloat($(this).val());
var price = parseFloat($price.val());
var calcPrice = parseFloat((price * percentage / 100).toFixed(2));
var newPrice = price + calcPrice;
$increase.text(newPrice);
$increaseWrap.fadeIn();
if (isNaN(newPrice)) {
$increaseWrap.hide();
}
}
function calculatePerc() {
var percentage = $percentage.val();
var price = parseFloat($(this).val());
var calcPerc = parseFloat((price * percentage / 100).toFixed(2));
var newPrice = price + calcPerc;
$increase.text(newPrice);
}
function removePercent() {
$increaseWrap.fadeOut();
}
}
percentageCal();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<fieldset class="wrapper-types__investment">
<legend class="sr-only">Investment 1</legend>
<div class="form-item form-item--required form-item--invamt">
<label class="form-item__label" for="wrappers[0]">Investment amount</label>
<div class="form-item__input-labelled">
<span class="form-item__input-label">£</span>
<input class="form-item__input " type="number" name="wrappers[0]" id="wrappers[0]" min="0" value="15000" required>
</div>
</div>
<div class="form-item form-item--charges-wrap">
<span class="form-item__label">Charges</span>
<div class="form-item form-item--charges">
<label class="form-item__input-label-expand" for="percentage1">%</label>
<div class="form-item__input-expand">
<input class="form-item__input percentage" type="number" name="percentage" id="percentage1">
</div>
</div>
</div>
<div class="form-item form-item--charges-wrap">
<span class="wrapper-types__percentage">= £<span class="wrapper-types__percentage-value"></span></span>
</div>
<div class="form-item form-item--action-btns">
</div>
</fieldset>
<fieldset class="wrapper-types__investment">
<legend class="sr-only">Investment 2</legend>
<div class="form-item form-item--required form-item--invamt">
<label class="form-item__label" for="wrappers[1]">Investment amount</label>
<div class="form-item__input-labelled">
<span class="form-item__input-label">£</span>
<input class="form-item__input " type="number" name="wrappers[1]" id="wrappers[1]" min="0" value="13005.02" required>
</div>
</div>
<div class="form-item form-item--charges-wrap">
<span class="form-item__label">Charges</span>
<div class="form-item form-item--charges">
<label class="form-item__input-label-expand" for="percentage2">%</label>
<div class="form-item__input-expand">
<input class="form-item__input percentage" type="number" name="percentage" id="percentage2">
</div>
</div>
</div>
<div class="form-item form-item--charges-wrap">
<span class="wrapper-types__percentage">= £<span class="wrapper-types__percentage-value"></span></span>
</div>
<div class="form-item form-item--action-btns">
</div>
</fieldset>
Instead of IDs, use classes and DOM traversal functions to find the fields in the same fieldset.
function percentageCal() {
var $price = $(".form-item--invamt .form-item__input").on("input", calculatePerc),
$percentage = $(".form-item__input-expand .percentage").on("input", calculatePrice),
$currency = $(".form-item__input-expand .currency").on("focus", removePercent),
$none = $(".form-item--charges .no-charge").on("focus", removePercent),
$increase = $(".wrapper-types__percentage-value"),
$increaseWrap = $(".wrapper-types__percentage");
$percentage.add($currency).keypress(function(event) {
if (event.which != 8 && event.which != 0 && (event.which < 48 || event.which > 57)) {
return false;
}
});
function calculatePrice() {
var $fieldset = $(this).closest("fieldset");
var percentage = parseFloat($(this).val());
var price = parseFloat($fieldset.find(".form-item--invamt .form-item__input").val());
var calcPrice = parseFloat((price * percentage / 100).toFixed(2));
var newPrice = price + calcPrice;
$fieldset.find(".wrapper-types__percentage-value").text(newPrice);
$fieldset.find(".wrapper-types__percentage").fadeIn();
if (isNaN(newPrice)) {
$fieldset.find(".wrapper-types__percentage").hide();
}
}
function calculatePerc() {
var $fieldset = $(this).closest("fieldset");
var percentage = $fieldset.find(".form-item__input-expand .percentage").val();
var price = parseFloat($(this).val());
var calcPerc = parseFloat((price * percentage / 100).toFixed(2));
var newPrice = price + calcPerc;
$fieldset.find(".wrapper-types__percentage-value").text(newPrice);
}
function removePercent() {
var $fieldset = $(this).closest("fieldset");
$fieldset.find(".wrapper-types__percentage").fadeOut();
}
}
percentageCal();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<fieldset class="wrapper-types__investment">
<div class="form-item--invamt">
<div>
<span class="form-item__input-label">£</span>
<input class="form-item__input " type="number" name="wrappers[0]" id="wrappers[0]" min="0" value="15000" required>
</div>
</div>
<div class="form-item--charges-wrap">
<div class="form-item--charges">
<label class="form-item__input-label-expand" for="percentage">%</label>
<div class="form-item__input-expand">
<input class="form-item__input percentage" type="number" name="percentage" id="percentage">
</div>
</div>
</div>
<div class="form-item--charges-wrap">
<span class="wrapper-types__percentage">= £<span class="wrapper-types__percentage-value"></span></span>
</div>
</fieldset>
<fieldset class="wrapper-types__investment">
<div class="form-item--invamt">
<div>
<span class="form-item__input-label">£</span>
<input class="form-item__input " type="number" name="wrappers[1]" id="wrappers[1]" min="0" value="15000" required>
</div>
</div>
<div class="form-item--charges-wrap">
<div class="form-item--charges">
<label class="form-item__input-label-expand" for="percentage1">%</label>
<div class="form-item__input-expand">
<input class="form-item__input percentage" type="number" name="percentage" id="percentage1">
</div>
</div>
</div>
<div class="form-item--charges-wrap">
<span class="wrapper-types__percentage">= £<span class="wrapper-types__percentage-value"></span></span>
</div>
</fieldset>
I'm just trying to make this check form validation. Like it shouldn't let the form submit unless everything is filled in, then it should do the total only if it works. I'm new to this and I have no idea what is going on, but it is just showing a blue box at the top of my screen by default, and then submitting/accepting regardless of the form being filled out or not.
HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Hands-on Project 6 - Order</title>
<link rel="stylesheet" href="styles.css">
<script src="script.js"></script>
</head>
<body>
<section>
<article>
<h2>Pizza Order Form</h2>
<div id="errorMessage">
</div>
<form action="results.html" id="orderForm">
<input type="hidden" name="hidden" id="hidden">
<fieldset>
<legend>Delivery Information</legend>
<label for="nameinput">Name</label>
<input type="text" id="nameinput" name="name">
<label for="addrinput">Street Address</label>
<input type="text" id="addrinput" name="address">
<label for="cityinput">City</label>
<input type="text" id="cityinput" name="city">
<label for="emailinput">Email</label>
<input type="email" id="emailinput" name="email">
<label for="phoneinput">Phone</label>
<input type="tel" id="phoneinput" name="phone">
</fieldset>
<fieldset>
<legend>Order</legend>
<p>
<span class="nonLabel">What type of crust:</span>
<br>
<input type="radio" name="crust" id="thin" value="1">
<label for="thin">Thin Crust</label>
<input type="radio" name="crust" id="original" value="0">
<label for="original">Original Crust</label>
<input type="radio" name="crust" id="thick" value="3">
<label for="thick">Deep Dish</label>
</p>
<label for="size" class="nonLabel">What size pizza:</label>
<select id="size" name="size">
<option value=""> </option>
<option value="small">Small</option>
<option value="medium">Medium</option>
<option value="large">Large</option>
<option value="XL">Extra Large</option>
</select>
<p>
<span class="nonLabel">What topping(s):</span>
<br>
<input type="checkbox" id="pepperoni" name="toppings" value="Pepperoni">
<label for="pepperoni">Pepperoni</label>
<input type="checkbox" id="sausage" name="toppings" value="Sausage">
<label for="sausage">Sausage</label>
<input type="checkbox" id="bacon" name="toppings" value="Bacon">
<label for="bacon">Bacon</label>
<br>
<input type="checkbox" id="greenpep" name="toppings" value="Green Peppers">
<label for="greenpep">Green Peppers</label>
<input type="checkbox" id="onion" name="toppings" value="Onions">
<label for="onion">Onions</label>
<input type="checkbox" id="xcheese" name="toppings" value="Extra Cheese">
<label for="xcheese">Extra Cheese</label>
</p>
<p>
<label for="instructions" id="instrlabel">Special Instructions:</label>
</p>
<textarea id="instructions" name="instructions" rows="3" cols="60"
placeholder="Special Requests, Delivery Details"></textarea>
</fieldset>
<fieldset id="submitbutton">
<input type="submit" id="submitBtn" value="Add to Cart">
</fieldset>
</form>
</article>
</section>
<script>
document.getElementById("submitBtn ").addEventListener("submit",
validateForm(evt));
</script>
</body>
</html>
JavaScript:
// validate required fields
function validateForm(evt){
if(evt.preventDefault){
evt.preventDefault();
}
else {
evt.returnValue = false;
}
formValidity = true;
validateFormControls();
}
function validateFormControls(){
var inputElements = document.querySelectorAll("fieldset:first-of-type
input");
var errorDiv = document.getElementById("errorMessage");
var crustBoxes = document.getElementsByName("crust");
var fieldsetValidity = true;
var elementCount = inputElements.length;
var currentElement;
try {
for(var i = 0; i < elementCount; i++){
currentElement = inputElements[i];
if(currentElement.value === ""){
currentElement.style.border = "3px solid #0B907A";
currentElement.style.backgroundColor = "#FFC58A";
fieldsetValidity = false;
}
else {
currentElement.style.border = "";
currentElement.style.backgroundColor = "";
}
}
currentElement.querySelectorAll("select")[0];
if (currentElement.selectedIndex === 0){
currentElement.style.border = "3px solid #0B907A";
currentElement.style.backgroundColor = "#FFC58A";
fieldsetValidity = false;
}
else{
currentElement.style.border = "";
currentElement.style.backgroundColor = "";
}
if (!crustBoxes[0].checked && !crustBoxes[1].checked &&
!crustBoxes[2].checked){
crustBoxes[0].style.outline = "3px solid #0B907A";
crustBoxes[1].style.outline = "3px solid #0B907A";
crustBoxes[2].style.outline = "3px solid #0B907A";
}
else {
crustBoxes[0].style.outline = "";
crustBoxes[1].style.outline = "";
crustBoxes[2].style.outline = "";
}
if (fieldsetValidity === false){
throw "Please complete all required fields.";
}
else {
errorDiv.style.display = "none";
errorDiv.innerHTM = "";
}
catch(msg){
errorDiv.style.display = "block";
errorDiv.innerHTML = msg;
formValidity = false;
}
}
}
function orderTotal(){
var itemTotal = 5;
var crusts = document.getElementsByName("crust");
var toppings = document.getElementsByName("goodnight");
var sizes = document.querySelectorAll("select")[0];
if (sizes.selectedIndex > 0) {
itemTotal += ((sizes.selectedIndex * 1) * 2);
}
for (var i=0; i < toppings.length; i++){
if (toppings[i].checked) {
itemTotal += 1;
}
}
for (var i=0; i < crusts.length; i++){
if (crusts[i].checked) {
itemTotal += (crusts[i].value * 1);
}
}
alert ("Your order total is $" + itemTotal);
document.getElementById("hidden").value = itemTotal;
}
Wrong id parameter
document.getElementById("submitButton ").addEventListener("submit", validateForm(evt));
Must be
document.getElementById("submitBtn").addEventListener("submit",validateForm(evt));
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;