Matching dropdown quantity and calculating total price - javascript

I want to select the number of person attending and it must be matched with meal quantity.
User must specify whether vegetarian meal or non-vegetarian. A veg meal costs $5 while a non-veg meal cost $10. For example, if there's 3 person attending with 2 vegetarian and 1 non-vegetarian, the total price of meal will be $20 total. Also the meal quantity options must have only 3 person in total. How do I do this in Javascript only?
How do I display the final price also?
function validate() {
var dn = document.getElementById("dropDN").value;
return false;
}
function showInput() {
document.getElementById('displaydn').innerHTML =
document.getElementById("dropDN").value;
}
<form class="myForm" onsubmit="return validate();">
Number of person attending:
<select id="dropDN">
<option value="">Select one</option>
<option value="One">1</option>
<option value="Two">2</option>
<option value="Three">3</option>
<option value="Four">4</option>
</select>
<br />
<br />Meal Quantity Options: Vegetarian
<input type="checkbox" onclick="" name="" id="veg">
<input type="number" max="4" />
<br /> Non-Vegetarian
<input type="checkbox" onclick="" name="" id="nonveg">
<input type="number" max="4" />
<br />
<br />
<br />
<input type="submit" onclick="showInput()">
<br>
<br> Number of person attending: <span id="displaydn"> </span>
<br />
</form>

Listen to the change event for both input controls.
When they change, update the respective global variable (either vegetarian or nonVegetarian and then update the total meals and cost values.
var vegetarian = 0;
var nonVegetarian = 0;
var cost = 0.00;
document.querySelector('#veg').addEventListener('change', function(e)
{
vegetarian = parseInt(document.querySelector('#veg').value, 10);
if(vegetarian + nonVegetarian > 4) // Make sure we never have more than 4 customers
{
nonVegetarian--;
document.querySelector('#nonveg').value = nonVegetarian;
}
update();
});
document.querySelector('#nonveg').addEventListener('change', function(e)
{
nonVegetarian = parseInt(document.querySelector('#nonveg').value, 10);
if(vegetarian + nonVegetarian > 4) // Make sure we never have more than 4 customers
{
vegetarian--;
document.querySelector('#veg').value = vegetarian;
}
update();
});
var update = function()
{
document.querySelector('#attending').innerText = vegetarian + nonVegetarian;
document.querySelector('#cost').innerText = (vegetarian*5) + (nonVegetarian *10);
};
update();
<form class="myForm" onsubmit="return validate();">
Meal Quantity Options: Vegetarian
<input id="veg" type="number" min="0" max="4" value="0" /><br />
Non-Vegetarian
<input id="nonveg" type="number" min="0" max="4" value="0" /><br />
<br />
<br> Number of people attending: <span id="attending"></span>
<br> Cost : $<span id="cost"></span>
<br />
</form>

Related

Why does the recalculation of the form drop the first javascript calculation?

I am trying to recalculate the form based on a payment method. What I have is sort of working. It fails however if the payment method is changed after entering the number of widgets needed. The widget 2 value stays intact but the widget 1 calculation reverts to 0 yet the entered number is still in the number of widgets needed for Widget 1.
function lf(vntAmount) {
vntAmount = parseFloat(vntAmount) || 0; // find number (parseFloat) switch it to 0 if not a number
vntAmount = vntAmount * 100; // cost of widget 1
document.frmConvert.box1.value = vntAmount.toFixed(2)
}
function rf(vntAmount) {
vntAmount = parseFloat(vntAmount) || 0; // find number (parseFloat)
vntAmount = vntAmount * 200; // cost of widget 2
document.frmConvert.box2.value = vntAmount.toFixed(2)
}
function calculate() {
var myBox1 = document.getElementById('box1').value;
var myBox2 = document.getElementById('box2').value;
// var result = document.getElementById('result'); // don't know what this does
if (document.getElementById('visa_checked').checked) {
var myResult = (parseFloat(myBox1) + parseFloat(myBox2)) * .15;
} else {
var myResult = (parseFloat(myBox1) + parseFloat(myBox2)) * .12;
}
var myResult2 = myResult + (parseFloat(myBox1) + parseFloat(myBox2));
result.value = myResult.toFixed(2);
result2.value = '$' + myResult2.toFixed(2);
}
body {
font-family: arial;
font-size: 100%;
color: #aea2a2
}
<html>
<head>
<title>Test Form</title>
<script type="text/javascript">
onload = function() {
location.href = "#";
}
</script>
</head>
<body>
<FORM ACTION="processform.php" METHOD=POST name="frmConvert">
<h4>Widgets For Sale</h4>
Mandatory field *<br><br> Name*
<br>
<input type="text" name="sheetdata[]" size="42"><br><br> Address
<br>
<input type="text" name="sheetdata[]" size="42"><br><br> City
<br>
<input type="text" name="sheetdata[]" size="42"><br><br> Postal Code<br>
<input type="text" name="sheetdata[]" size="42"><br><br> Email
<br>
<input type="text" name="sheetdata[]" size="42"><br><br> Phone*
<br>
<input type="text" name="sheetdata[]" size="42"><br><br> Method of payment<br>
<input type="radio" name="sheetdata[]" value="Visa" id="visa_checked" onChange="lf(this.value);calculate();">Visa<br>
<input type="radio" name="sheetdata[]" value="Cheque" onChange="lf(this.value);calculate();">Cheque<br>
<input type="radio" name="sheetdata[]" value="E-Transfer" onChange="lf(this.value);calculate();" checked>E Transfer<br>
<br><br> Number of Widget One needed:<br>
<input name="sheetdata[]" id="txtAmount" type="text" value="" onchange="lf(this.value);calculate();" size="3" value="0" /> # $100 <input name="sheetdata[]" size="5" readonly="readonly" id="box1" value="0" />
<br><br> Number of Widget Two needed<br>
<input name="sheetdata[]" id="txtAmount2" type="text" value="" onChange="rf(this.value);calculate();" size="3" value="0" /> # $200 <input name="sheetdata[]" size="5" readonly="readonly" id="box2" value="0" />
<br><br> Tax 12% <input name="sheetdata[]" id="result" size="5" readonly="readonly" /> 3 % added for Credit Card
<br><br> Total <input name="sheetdata[]" id="result2" size="5" readonly="readonly" />
<input type="hidden" name="sheet_name" value="Test_Form">
<p><input type="submit" value="Submit" name="B1"><input type="reset" value="Reset" name="B2"></p>
<p>Thank You!</p>
</form>
</body>
</html>
Not sure what to try to fix this.

Textbox value not being multiplied when checkbox selected (HTML & Javascript/JQuery)

My code updates the CPC textbox when options are selected, but when an agency discount is selected (i.e. the 10% checkbox), it successfully lowers the CPC textbox value by 10% but does not do the same for the Total Cost textbox.
The Total Cost textbox value should be the (CPC textbox value * number of clicks textbox) * percentdiscount multiplier
Can anyone see where I'm going wrong? I'll be happy to clarify further if I haven't explained this very well!
HTML:
<div class="runningtotal">
Running CPC Total (in £): <input id="sum" type="text" readonly="true" value="0.00" data-total="0" />
Total Cost (in £): <input id="totalcost" type="text" readonly="true" value="0 (until clicks specified)" data-total="0" />
</div>
<div class="black_whitelisting">
<h1>4. Blacklist/Whitelist?</h1>
<input type="checkbox" class="blacklist" name="blacklist" value="0.20" id="blacklist_checkbox" onclick="BlacklistFunction()">Blacklist required<br>
<input type="checkbox" class="whitelist" name="whitelist" value="0.30" id="whitelist_checkbox">Whitelist required<br>
</div>
<div class="selecttier">
<h1>5. Number of Clicks</h1>
<input id="numberofclickstextbox" type="text" value="0.00" data-total="0" oninput="calculatetier()" />
</div>
<div class="agencydiscount">
<h1>6. Agency Discount</h1>
<label>
<input type="radio" name="percentdiscount" value="1" checked>
None
</label>
<label>
<input type="radio" name="percentdiscount" id="10percent" value="0.9" onclick="calculatetotalcost10()" >
10% Discount
</label>
<label>
<input type="radio" name="percentdiscount" id="15percent" value="0.85" onclick="calculatetier15()" >
15% Discount
</label>
</div>
Javascript:
jQuery(function($) {
$('input[name="percentdiscount"]').on('change', function() {
applyDiscount();
});
$('input[type=checkbox]').click(function() {
let sum = 0;
$('input[type=checkbox]:checked').each(function() {
sum += parseFloat($(this).val());
});
$('#sum').val(sum.toFixed(2)).data('total', sum);
applyDiscount();
});
function applyDiscount() {
var pc = parseFloat($('input[name="percentdiscount"]:checked').val());
$('#sum').val(function() {
return ($(this).data('total') * pc).toFixed(2);
});
}
});
//to work out total cost
function calculatetier() {
var myBox5 = document.getElementById('numberofclickstextbox').value;
var myBox6 = document.getElementById('sum').value;
var result = document.getElementById('totalcost');
var myResult = myBox5 * myBox6;
result.value = myResult.toFixed(2);
}
Looks like you are calculatetier function isn't being called during the change of discount.
Working Demo: https://codepen.io/punith/pen/gOpaVxr?editors=1010
HTML code
<div class="runningtotal">
Running CPC Total (in £): <input id="sum" type="text" readonly="true" value="0.00" data-total="0" />
Total Cost (in £): <input id="totalcost" type="text" readonly="true" value="0 (until clicks specified)" data-total="0" />
</div>
<div class="black_whitelisting">
<h1>4. Blacklist/Whitelist?</h1>
<input type="checkbox" class="blacklist" name="blacklist" value="0.20" id="blacklist_checkbox" >Blacklist required<br>
<input type="checkbox" class="whitelist" name="whitelist" value="0.30" id="whitelist_checkbox">Whitelist required<br>
</div>
<div class="selecttier">
<h1>5. Number of Clicks</h1>
<input id="numberofclickstextbox" type="text" value="0.00" data-total="0" oninput="calculatetier()" />
</div>
<div class="agencydiscount">
<h1>6. Agency Discount</h1>
<label>
<input type="radio" name="percentdiscount" value="1" checked>
None
</label>
<label>
<input type="radio" name="percentdiscount" id="10percent" value="0.9" >
10% Discount
</label>
<label>
<input type="radio" name="percentdiscount" id="15percent" value="0.85" >
15% Discount
</label>
</div>
JS Code
function calculatetier() {
var myBox5 = document.getElementById('numberofclickstextbox').value;
var myBox6 = document.getElementById('sum').value;
var result = document.getElementById('totalcost');
if(myBox6=="0.00"){
myBox6 =1;
}
console.log(myBox6)
var myResult = myBox5 * myBox6;
result.value = myResult.toFixed(2);
}
jQuery(function($) {
$('input[name="percentdiscount"]').on('change', function() {
applyDiscount();
});
$('input[type=checkbox]').click(function() {
let sum = 0;
$('input[type=checkbox]:checked').each(function() {
sum += parseFloat($(this).val());
});
$('#sum').val(sum.toFixed(2)).data('total', sum);
applyDiscount();
});
//to work out total cost
function applyDiscount() {
var pc = parseFloat($('input[name="percentdiscount"]:checked').val());
$('#sum').val(function() {
return ($(this).data('total') * pc).toFixed(2);
});
calculatetier()
}
});
try to use onchange event instead I guess the event you are binding is not correct
<input id="numberofclickstextbox" type="text" value="0.00" data-total="0" onchange="calculatetier()" />

Getting Uncaught ReferenceError

I keep on getting this error Uncaught ReferenceError: calculatePrice is not defined at HTMLInputElement.onclick.
I have already seen the other answers on here regarding this error and none of them worked. I tried defining the script in body or head, didn't make a difference. I also think the function and button I connect it to are correct as I compared to a solution, so I really don't know why it is not working when I press it.
<html>
<head>
<link href="style/myStyles.css" type="text/css" rel="stylesheet">
<title> The Printing Company </title>
</head>
<body>
<script type="text/javascript"></script>
<script>
function calculatePrice() {
var quantity, type, price
quantity = document.getElementById("qty").value;
type = document.getElementById("cardstype").value;
if (type.includes("Basic"){
price = 10*(quantity/100);
} else if (type.includes("Medium"){
price = 15*(quantity/100);
} else if (type.includes("High"){
price = 20*(quantity/100);
}
alert("Your order will cost " + price + " GBP.");
}
</script>
<form action="form.php" method="post">
<label >Company Name</label><br>
<input name="name" type="text" required /><br>
<br>
<label>Contact email</label><br>
<input name="email" type="email" required /><br>
<br>
<label>Business Card type</label><br>
<select name="cardstype" id="cardstype">
<option value="" disabled selected>-Select Card Quality-</option>
<option value="Basic Quality">Basic Quality</option>
<option value="Medium Quality">Medium Quality</option>
<option value="High Quality">High Quality</option>
</select><br>
<br>
<label>Business Cards quantity</label><br>
<input name="qty" id ="qty" type="number" required Onchange = '
if( !( this.value >= 100 && this.value <= 1000 ) ) {
//alert the user that they have made a mistake
alert( this.value + " is not a valid quantity. Minimun quantity per order: 100 and maximum: 1000.");
this.value=""; //clears the text box
}'><br>
<br>
<input type="button" name="Price" value="Calculate Price" onclick="calculatePrice()"/>
<input type="submit" value="Submit Order"/>
</form>
</html>
Can anyone help?
I think You are missing the closing parentheses in your if statements:
if (type.includes("Basic") {
^^^ here
Working example:
function calculatePrice() {
var quantity, type, price;
quantity = document.getElementById("qty").value;
type = document.getElementById("cardstype").value;
if (type.includes("Basic")) {
price = 10*(quantity/100);
} else if (type.includes("Medium")) {
price = 15*(quantity/100);
} else if (type.includes("High")) {
price = 20*(quantity/100);
}
alert("Your order will cost " + price + " GBP.");
}
<form action="form.php" method="post">
<label >Company Name</label><br>
<input name="name" type="text" required /><br>
<br>
<label>Contact email</label><br>
<input name="email" type="email" required /><br>
<br>
<label>Business Card type</label><br>
<select name="cardstype" id="cardstype">
<option value="" disabled selected>-Select Card Quality-</option>
<option value="Basic Quality">Basic Quality</option>
<option value="Medium Quality">Medium Quality</option>
<option value="High Quality">High Quality</option>
</select><br>
<br>
<label>Business Cards quantity</label><br>
<input name="qty" id ="qty" type="number" required Onchange = '
if( !( this.value >= 100 && this.value <= 1000 ) ) {
//alert the user that they have made a mistake
alert( this.value + " is not a valid quantity. Minimun quantity per order: 100 and maximum: 1000.");
this.value=""; //clears the text box
}'><br>
<br>
<input type="button" name="Price" value="Calculate Price" onclick="calculatePrice(event)"/>
<input type="submit" value="Submit Order"/>
</form>
You have a few typos in your function:
Missing closing curly brace (looks fixed now)
Missing semicolon after variable definition: var quantity, type, price;
Mismatched parentheses in if/elseif conditions (3 times): if (type.includes("Basic")) {
The below code has these problems fixed:
<script>
function calculatePrice() {
var quantity, type, price;
quantity = document.getElementById("qty").value;
type = document.getElementById("cardstype").value;
if (type.includes("Basic")){
price = 10*(quantity/100);
} else if (type.includes("Medium")){
price = 15*(quantity/100);
} else if (type.includes("High")){
price = 20*(quantity/100);
}
alert("Your order will cost " + price + " GBP.");
}
</script>
Therefore, the function calculatePrice isn't defined and can't be called.

Javascript Unit converter lb to kg

I am trying to implement a weight converter that takes pounds(lb) and converts it to kg and vice-versa in the total, I can't seem to get the logic of it right, here is my code, I don't want to use any libraries or frameworks because I want to learn the fundamentals of JavaScript, and also don't know how to implement the discount option.
Here is what I was able to do.
var appleWeight = +document.getElementById('weight1').value;
var orangeWeight = +document.getElementById('weight2').value;
var grapeWeight = +document.getElementById('weight3').value;
var bananaWeight = +document.getElementById('weight4').value;
var totalWeight = appleWeight + orangeWeight + grapeWeight + bananaWeight;
document.getElementById('total_weight').innerHTML = totalWeight;
console.log(totalWeight)
var applePrice = +document.getElementById('price1').value;
var orangePrice = +document.getElementById('price2').value;
var grapePrice = +document.getElementById('price3').value;
var bananaPrice = +document.getElementById('price4').value;
var totalPrice = applePrice + orangePrice + grapePrice + bananaPrice;
var discount = document.getElementById('discount').value;
var discountAmount = (totalPrice * Number(discount)) / 100
var finalPrice = totalPrice - discountAmount
document.getElementById('total_price').innerHTML = finalPrice;
console.log("total price " + totalPrice)
var lb = document.getElementsByTagName('select'.value)
<h1>JS Grocery Shop</h1>
<span class="label">Apple</span> <input type="number" name="weight" id="weight1" value="3.5" />
<select><option>kg</option><option class="lb" value="lb">lb</option></select> # $<input type="number" name="price" id="price1" value="2.3" /><br />
<span class="label">Orange</span><input type="number" name="weight" id="weight2" value="5" />
<select><option>kg</option><option class="lb" value="lb">lb</option></select> # $<input type="number" name="price" id="price2" value="3.0" /><br />
<span class="label">Grape</span> <input type="number" name="weight" id="weight3" value="2.0" />
<select><option>kg</option><option class="lb" value="lb">lb</option></select> # $<input type="number" name="price" id="price3" value="1.5" /><br />
<span class="label">Banana</span><input type="number" name="weight" id="weight4" value="1" />
<select><option>kg</option><option class="lb" value="lb">lb</option></select> # $<input type="number" name="price" id="price4" value="0.5" /><br /> Discount : <select id="discount">
<option value="0">0</option>
<option value="5">5%</option>
<option value="10">10%</option>
<option value="15">15%</option>
<option value="20">20%</option>
</select>
<br><br> Total Price : <span id="total_price"></span><br /> Total Weight : <span id="total_weight"></span>

Multiply total orders to quantity of order in jquery

I have a jquery that multiplies the price to quantity. Now I wanted to multiply the total of that to how many orders a costumer would place. Where would I insert my multiplication code? Here's how i envisioned the equation would be total=(price*quantity)*numberoforders. Here's a jfiddle of what I cant eloquently explain
Here's my code:
HTML
<form>
<ul>
<li>
<label>
<input type="checkbox" name="drink[]" class="drink" value="DrinkName1" data-price="12" /> Sample Item
<input min="0" max="5" type="number" class="quantity" name="quantity" value="1" />
</label>
</li>
<li>
<label>
<input type="checkbox" name="drink[]" class="drink" value="DrinkName2" data-price="6" /> Sample Item
<input min="0" max="5" type="number" class="quantity" name="quantity" value="1" />
</label>
</li>
<li>
<label>
<input type="checkbox" name="drink[]" class="drink" value="DrinkName3" data-price="4" /> Sample Item
<input min="0" max="5" type="number" class="quantity" name="quantity" value="1" />
</label>
</li>
<li>
<label>
Quantity of Orders
<input min="0" max="5" type="number" class="totalquant" name="quantity" value="1" />
</label>
</li>
</ul>
</form>
<p>Total</p>
<div id="totalDiv">0</div>
Jquery
$('.quantity, .drink').change(calculateTotal);
function calculateTotal() {
var $form = $(this).closest('form'), total = 0;
$form.find('.drink:checked').each(function() {
total += $(this).data('price') * parseInt($(this).next('.quantity').val() || 0, 10);
});
$('#totalDiv').text(total)* parseInt($(this).siblings('.totalquant').val() || 0, 10);
}
Appreciate all the help
I've made some changes on your code here https://jsfiddle.net/k91d23p6/3/
Basically, you have to multiply the total by the totalQuant after the forEach.
//query the DOM once, instead of on every change
var $form = $('form'); //on a real app it would be better to have a class or ID
var $totalQuant = $('.totalquant', $form);
var totalDiv = $('#totalDiv');
$('.quantity, .drink, .totalquant', $form).change(calculateTotal);
function calculateTotal() {
var total = 0;
$form.find('.drink:checked').each(function() {
total += $(this).data('price') * parseInt($(this).next('.quantity').val() || 0, 10);
});
var totalQuant = total * parseInt( $totalQuant.val() || 0, 10);
totalDiv.text(totalQuant);
}

Categories

Resources