I want to create a coffee shop transaction form. I've tried everything i know. but still nothing. this is a test design I have here the Item Name and Item Size. Each item will have different prices, example: Item X (size a = 5, size b = 10, size c = 15), Item Y (size a = 6, size b = 11, size c = 12)... then a quantity will be entered, after clicking the "ADD ITEM" button, the sub Total(not sure) should appear on the boxes on the left.
how should i make this work? thanks.
PS: sorry if you find it hard to understand what i say. thanks tho!
just to add, i used the sizes offered by star bucks.
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css" >
<link rel="stylesheet" type="text/css" href="sbwadcss.css">
<script type="text/javascript">
var TotalPrice=0;
function chooseItem()
{
var itemPrice = parseInt(0);
var itemName = document.getElementById('itemName').value;
var itemSize = document.getElementById('itemSize').value;
var qty = document.getElementById('QuanVal').value.trim();
var subTotal = document.getElementById('subTotal').value;
if (qty!="")
{
if (qty.match(/^[0-9]+$/))
{
if(itemName=="Caffe Latte")
{
if(itemSize=="Tall")
itemPrice = (75*qty);
else if(itemSize=="Grande")
itemPrice = (105*qty);
else(itemSize=="Venti")
itemPrice = (135*qty);
}
if(itemName=="Caffe Americano")
{
if(itemSize=="Tall")
itemPrice = (80*qty);
else if(itemSize=="Grande")
itemPrice = (100*qty);
else(itemSize=="Venti")
itemPrice = (120*qty);
}
if(itemName=="Cappuccino")
{
if(itemSize=="Tall")
itemPrice = (70*qty);
else if(itemSize=="Grande")
itemPrice = (95*qty);
else(itemSize=="Venti")
itemPrice = (120*qty);
}
if(itemName=="Espresso")
{
if(itemSize=="Tall")
itemPrice = (85*qty);
else if(itemSize=="Grande")
itemPrice = (105*qty);
else(itemSize=="Venti")
itemPrice = (125*qty);
}
if(itemName=="Flat White")
{
if(itemSize=="Tall")
itemPrice = (75*qty);
else if(itemSize=="Grande")
itemPrice = (100*qty);
else(itemSize=="Venti")
itemPrice = (125*qty);
}
}
document.getElementById("subTotal").value = itemPrice;
TotalPrice+=itemPrice;
if(itemName=="Caffe Latte")
{
document.getElementById('itemName').value += "\n" + "Caffe Latte" ;
document.getElementById('price').value += "\n" + itemPrice;
document.getElementById('qty').value += "\n" + qty;
document.getElementById('TotalPrice').value = TotalPrice;
}
else if(itemName=="Caffe Americano")
{
document.getElementById('itemName').value += "\n" + "Caffe Americano" ;
document.getElementById('price').value += "\n" + itemPrice;
document.getElementById('qty').value += "\n" + qty;
document.getElementById('TotalPrice').value = TotalPrice;
}
else if(itemName=="Cappuccino")
{
document.getElementById('itemName').value += "\n" + "Cappuccino" ;
document.getElementById('price').value += "\n" + itemPrice;
document.getElementById('qty').value += "\n" + qty;
document.getElementById('TotalPrice').value = TotalPrice;
}
else if(itemName=="Espresso")
{
document.getElementById('itemName').value += "\n" + "Espresso" ;
document.getElementById('price').value += "\n" + itemPrice;
document.getElementById('qty').value += "\n" + qty;
document.getElementById('TotalPrice').value = TotalPrice;
}
else
{
document.getElementById('itemName').value += "\n" + "Flat White" ;
document.getElementById('price').value += "\n" + itemPrice;
document.getElementById('qty').value += "\n" + qty;
document.getElementById('TotalPrice').value = TotalPrice;
}
}
else
alert("Invalid Quantity!!");
}
else
alert("Please Enter Quantity!!");
function Payment()
{
var payment = document.getElementById('paymnet').value.trim();
var TotalPrice = document.getElementById('TotalPrice').value;
if (payment !="")
{
if (payment.match(/^[0-9]+$/))
{
if (TotalPrice < payment)
{
var change = payment - TotalPrice;
document.getElementById('change').value= "Php" + change + ".00";
TotalPrice=0;
}
else
alert("Invalid Amount Entered!!");
}
else
alert("Invalid Amount Entered!!");
}
else
alert("Please Entered!!");
}
function NewTransaction(targ1,targ2,targ3)
{
var OK = confirm("Are you sure you want to make New Transaction? \n OK or CANCEL? ");
if (OK==true)
targ1.value="";
targ2.value="";
targ3.value="";
TotalPrice=0;
document.getElementById('itemName').value ="";
document.getElementById('price').value ="";
document.getElementById('qty').value ="";
document.getElementById('TotalPrice').value ="";
document.getElementById('payment').value="";
document.getElementById('change').value="";
}
</head>
<body>
<div id="form">
<legend class="wrap"><h3>COFFEE SHOP!</h3></legend>
<h4>TRANSACTION FORM</h4>
<div class="content">
<div class="left">
Item Name:
</div>
<div class="right">
<select id="itemName">
<option selected disabled="disabled">SELECT ITEM</option>
<option>Caffe Latte</option>
<option>Caffe Americano</option>
<option>Cappuccino</option>
<option>Espresso</option>
<option>Flat White</option>
</select>
</div>
</div>
<div class="content">
<div class="left">
Item Size:
</div>
<div class="right">
<select id="itemSize">
<option selected disabled="disabled">SELECT SIZE</option>
<option>Tall</option>
<option>Grande</option>
<option>Venti</option>
</select>
</div>
</div>
<div class="content">
<div class="left">
Quantity:
</div>
<div class="right">
<input type="text" id="QuanVal">
</div>
</div>
<div class="content">
<div class="left">
Price:
</div>
<div class="right">
<input type="text" id="subTotal" disabled="disabled">
</div>
</div>
<div class="btnContent">
<input type="button" value="ADD ITEM" onclick="AddItem()" style="background-color: grey; margin:3px; border-radius: 5px;">
</div>
<div class="btnContent">
<input type="button" value="NEW TRANSACTION" onclick="NewTransaction(document.getElementById('itemName'),document.getElementById('QuanVal'),document.getElementById('subTotal'))" style="background-color: grey; margin:3px; border-radius: 5px;">
</div>
</div>
<div id="form2">
<div class="content">
<div class="inline-div">
<p align="center">Item Name</p>
<textarea cols="15" rows="15" class="inline-txtarea" id="itemName" disabled="disable"></textarea>
</div>
<div class="inline-div">
<p align="center">Price</p>
<textarea cols="15" rows="15" class="inline-txtarea" id="price" disabled="disable"></textarea>
</div>
<div class="inline-div">
<p align="center">Quantity</p>
<textarea cols="15" rows="15" class="inline-txtarea" id="qty" disabled="disable"></textarea>
</div>
</div>
<div class="btnContent" style="width: 180px; padding-top: 5px;">
TOTAL PRICE:
<input type="text" id="TotalPrice" disabled="disabled">
</div>
<div class="btnContent" style="width: 180px; padding-left: 18px; padding-top: 5px;">
ENTER PAYMENT:
<input type="text" id="payment">
<input type="button" value="SUBMIT PAYMENT" onclick="Payment()" style="background-color: grey; margin:3px; border-radius: 5px;">
CHANGE :
<input type="text" id="change" disabled="disabled">
</div>
</div>
</body>
</html>
Maybe you use an object for the product's prices.
Changes:
using small variable and function names
id for collections
some other id
using an object for propducts and their size
exit early principle for checking requirements
collections does not show an empty line in advance
keeping totalPrice while payment
complete reseting all inputs in newTransaction
newTransaction without parameters
var totalPrice = 0,
products = {
"Caffe Latte": {
Tall: 75,
Grande: 105,
Venti: 135
},
"Caffe Americano": {
Tall: 80,
Grande: 100,
Venti: 120
},
Cappuccino: {
Tall: 70,
Grande: 95,
Venti: 120
},
Espresso: {
Tall: 85,
Grande: 105,
Venti: 125
},
"Flat White": {
Tall: 75,
Grande: 100,
Venti: 125
}
};
function addItem() {
var itemPrice,
itemName = document.getElementById('itemName').value,
itemSize = document.getElementById('itemSize').value,
quantity = document.getElementById('quantity').value.trim(),
subTotal = document.getElementById('subTotal').value;
if (!products[itemName]) {
alert("Please Enter Item Name!");
return;
}
if (!(itemSize in products[itemName])) {
alert("Please Enter Item Site!");
return;
}
if (quantity === "") {
alert("Please Enter Quantity!");
return;
}
if (!quantity.match(/^[0-9]+$/)) {
alert("Invalid Quantity!!");
return;
}
itemPrice = quantity * products[itemName][itemSize];
totalPrice += itemPrice;
document.getElementById("subTotal").value = itemPrice;
document.getElementById('collectionItemName').value += itemName + "\n";
document.getElementById('collectionPrice').value += products[itemName][itemSize] + "\n";
document.getElementById('collectionQuantity').value += quantity + "\n";
document.getElementById('totalPrice').value = totalPrice;
}
function payment() {
var payment = document.getElementById('payment').value.trim(),
change;
if (!payment) {
alert("Please Enter Payment!");
return;
}
if (!payment.match(/^\d+$/)) {
alert("Invalid Amount Entered!");
return;
}
if (totalPrice > payment) {
alert("Payment is not enough!");
return;
}
change = payment - totalPrice;
document.getElementById('change').value = "Php" + change + ".00";
}
function newTransaction() {
var ok = confirm("Are you sure you want to make New Transaction? \n OK or CANCEL? ");
if (ok) {
totalPrice = 0;
document.getElementById('itemName').selectedIndex = 0;
document.getElementById('itemSize').selectedIndex = 0;
document.getElementById('subTotal').value = "";
document.getElementById('quantity').value = "";
document.getElementById("subTotal").value = "";
document.getElementById('collectionItemName').value = "";
document.getElementById('collectionPrice').value = "";
document.getElementById('collectionQuantity').value = "";
document.getElementById('totalPrice').value = "";
document.getElementById('payment').value = "";
document.getElementById('change').value = "";
}
}
<div id="form">
<h3>COFFEE SHOP!</h3>
<h4>TRANSACTION FORM</h4>
<div class="content">
<div class="left">Item Name:</div>
<div class="right">
<select id="itemName">
<option selected disabled="disabled">SELECT ITEM</option>
<option>Caffe Latte</option>
<option>Caffe Americano</option>
<option>Cappuccino</option>
<option>Espresso</option>
<option>Flat White</option>
</select>
</div>
</div>
<div class="content">
<div class="left">Item Size:</div>
<div class="right">
<select id="itemSize">
<option selected disabled="disabled">SELECT SIZE</option>
<option>Tall</option>
<option>Grande</option>
<option>Venti</option>
</select>
</div>
</div>
<div class="content">
<div class="left">Quantity:</div>
<div class="right"><input type="text" id="quantity"></div>
</div>
<div class="content">
<div class="left">Price:</div>
<div class="right"><input type="text" id="subTotal" disabled="disabled"></div>
</div>
<div class="btnContent">
<input type="button" value="ADD ITEM" onclick="addItem()" style="background-color: grey; margin:3px; border-radius: 5px;">
</div>
<div class="btnContent">
<input type="button" value="NEW TRANSACTION" onclick="newTransaction()" style="background-color: grey; margin:3px; border-radius: 5px;">
</div>
</div>
<div id="form2">
<div class="content">
<div class="inline-div">
<p align="center">Item Name</p>
<textarea cols="15" rows="15" class="inline-txtarea" id="collectionItemName" disabled="disabled"></textarea>
</div>
<div class="inline-div">
<p align="center">Price</p>
<textarea cols="15" rows="15" class="inline-txtarea" id="collectionPrice" disabled="disabled"></textarea>
</div>
<div class="inline-div">
<p align="center">Quantity</p>
<textarea cols="15" rows="15" class="inline-txtarea" id="collectionQuantity" disabled="disabled"></textarea>
</div>
</div>
<div class="btnContent" style="width: 180px; padding-top: 5px;">
TOTAL PRICE:
<input type="text" id="totalPrice" disabled="disabled">
</div>
<div class="btnContent" style="width: 180px; padding-left: 18px; padding-top: 5px;">
ENTER PAYMENT:
<input type="text" id="payment">
<input type="button" value="SUBMIT PAYMENT" onclick="payment()" style="background-color: grey; margin:3px; border-radius: 5px;">
CHANGE :
<input type="text" id="change" disabled="disabled">
</div>
</div>
Related
I continue to discover JavaScript and again I am faced with a small problem
In my order form, I have about 300 items and each item is wrapped by a div, in which there is a class color1
I would like when the quantity is greater than 0 inside my div that my div turns green.
It works great with a div.
But, if I submit the same class for my second item and the quantity of my item is greater than 0, my div does not turn green unless I add for example the color3 class
To better understand,
here is the extract of my code where I retrieve the quantity of the article and where I test this quantity, in order to give it the green color if quantity greater than 0.
In summary, what I want is that all the div or the whenitee is greater than 0 green silk.
$('.ajouter-panier').click(function(event) {
event.preventDefault();
var nom_option = "";
var prix_option = 0;
var url = $(this).data('url');
var option_checkbox = $(this).data('checkbox');
if (option_checkbox != "") {
var checkboxes = document.getElementsByClassName(option_checkbox);
for (var i = 0; i < checkboxes.length; i++) {
if (checkboxes[i].checked == true) {
var nom_option = nom_option + " (" + $(checkboxes[i]).data('nom') + ")";
var prix_option = prix_option + Number($(checkboxes[i]).data('prix'));
}
}
}
if ($(this).data('select')) {
var nom = $(this).data('nom') + " (" + document.getElementById("" + $(this).data('select') + "").value + ")" + nom_option;
} else var nom = $(this).data('nom');
var prix = Number($(this).data('prix')) + (prix_option);
if ($(this).attr('data-qte')) {
var qte_option = $(this).attr('data-qte');
MonPanier.ajouter_produit_dans_panier(nom, prix, qte_option, url);
} else MonPanier.ajouter_produit_dans_panier(nom, prix, 1, url);
var color = $(this).attr('data-qte');
console.log(color);
if (color > 0) {
const collection1 = document.getElementsByClassName("couleur1");
collection1[0].style.backgroundColor = "green";
const collection2 = document.getElementsByClassName("couleur2");
collection2[0].style.backgroundColor = "green";
} else {
const collection1 = document.getElementsByClassName("couleur1");
collection1[0].style.backgroundColor = "";
const collection2 = document.getElementsByClassName("couleur2");
collection2[0].style.backgroundColor = "";
}
afficherpanier();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="col-xl-2 col-lg-3 col-md-4 col-sm-6 couleur1" style="margin-bottom: 15px; padding-left: 5px; padding-right: 5px;">
<div class="card">
<div class="">
<h3 class="card-title centrer_titre_texte couleur2">2001</h3>
<div class="card-body stylecardbody" style="padding-top: 0;">
<div class="row mt-12">
<div class="col-md-12">
<select class="form-select styleselect" aria-label="2001" onchange="changeQte(this);">
<option selected value="1.10">1 sachet </option>
<option value="2">2 sachets</option>
<option value="3">3 sachets </option>
</select>
</div>
<a style="cursor: pointer; margin-bottom: 5px;width: 90%;display: block;margin-left: auto;margin-right: auto;" data-nom="2001" data-prix="1.10" data-qte="1" data-checkbox="2001" data-url="https://phil.pecheperle.be/image-perles/perle-verre-peche-gardon-2001.JPG"
class="btn btn-primary ajouter-panier b-items__item__add-to-cart" onclick="setTimeout(() => ouvreMaJolieAlert(event), 1000);"> ajouter au panier </a>
</div>
</div>
</div>
</div>
</div>
You should parse value of attribute to number.
var color = Number($(this).attr('data-qte'));
If you want to change <a> parent to color:green; on event onclick and if is set attribute (data-qte > 0) and apply it to multiple divs with class couleur1. Then the simpliest way to do this is to go to that element using event.currentTarget and parentElement
const collection1 = event.currentTarget.parentElement.parentElement.parentElement.parentElement.parentElement
if (color > 0) {
collection1.style.backgroundColor = "green";
} else {
collection1.style.backgroundColor = "";
}
full code:
$('.ajouter-panier').click(function (event) {
event.preventDefault();
var nom_option = "";
var prix_option = 0;
var url = $(this).data('url');
var option_checkbox = $(this).data('checkbox');
if (option_checkbox != "") {
var checkboxes = document.getElementsByClassName(option_checkbox);
for (var i = 0; i < checkboxes.length; i++) {
if (checkboxes[i].checked == true) {
var nom_option = nom_option + " (" + $(checkboxes[i]).data('nom') + ")";
var prix_option = prix_option + Number($(checkboxes[i]).data('prix'));
}
}
}
if ($(this).data('select')) {
var nom = $(this).data('nom') + " (" + document.getElementById("" + $(this).data('select') + "").value + ")" + nom_option;
} else var nom = $(this).data('nom');
var prix = Number($(this).data('prix')) + (prix_option);
if ($(this).attr('data-qte')) {
var qte_option = $(this).attr('data-qte');
} else MonPanier.ajouter_produit_dans_panier(nom, prix, 1, url);
var color = Number($(this).attr('data-qte'));
const collection1 = event.currentTarget.parentElement.parentElement.parentElement.parentElement.parentElement
const h1 = event.currentTarget.parentElement.parentElement.previousElementSibling
if (color > 0) {
collection1.style.backgroundColor = "green";
h1.style.color = "green";
} else {
collection1.style.backgroundColor = "";
h1.style.color = "";
}
afficherpanier();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.2.1/dist/css/bootstrap.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.2.1/dist/js/bootstrap.bundle.min.js"></script>
<div class="col-xl-2 col-lg-3 col-md-4 col-sm-6 couleur1"
style="margin-bottom: 15px; padding-left: 5px; padding-right: 5px;">
<div class="card">
<div class="">
<h3 class="card-title centrer_titre_texte couleur2">2001</h3>
<div class="card-body stylecardbody" style="padding-top: 0;">
<div class="row mt-12">
<div class="col-md-12">
<select class="form-select styleselect" aria-label="2001" onchange="changeQte(this);">
<option selected value="1.10">1 sachet </option>
<option value="2">2 sachets</option>
<option value="3">3 sachets </option>
</select>
</div>
<a style="cursor: pointer; margin-bottom: 5px;width: 90%;display: block;margin-left: auto;margin-right: auto;"
data-nom="2001" data-prix="1.10" data-qte="1" data-checkbox="2001"
data-url="https://phil.pecheperle.be/image-perles/perle-verre-peche-gardon-2001.JPG"
class="btn btn-primary ajouter-panier b-items__item__add-to-cart"
onclick="setTimeout(() => ouvreMaJolieAlert(event), 1000);"> ajouter au panier </a>
</div>
</div>
</div>
</div>
</div>
<div class="col-xl-2 col-lg-3 col-md-4 col-sm-6 couleur1"
style="margin-bottom: 15px; padding-left: 5px; padding-right: 5px;">
<div class="card">
<div class="">
<h3 class="card-title centrer_titre_texte couleur2">2001</h3>
<div class="card-body stylecardbody" style="padding-top: 0;">
<div class="row mt-12">
<div class="col-md-12">
<select class="form-select styleselect" aria-label="2001" onchange="changeQte(this);">
<option selected value="1.10">1 sachet </option>
<option value="2">2 sachets</option>
<option value="3">3 sachets </option>
</select>
</div>
<a style="cursor: pointer; margin-bottom: 5px;width: 90%;display: block;margin-left: auto;margin-right: auto;"
data-nom="2001" data-prix="1.10" data-qte="1" data-checkbox="2001"
data-url="https://phil.pecheperle.be/image-perles/perle-verre-peche-gardon-2001.JPG"
class="btn btn-primary ajouter-panier b-items__item__add-to-cart"
onclick="setTimeout(() => ouvreMaJolieAlert(event), 1000);"> ajouter au panier </a>
</div>
</div>
</div>
</div>
</div>
I need a little help here, so when i add an option from dynamic add select option and click order button it will display the options i picked.
For the next step, i need to count sum of the options i choose. I tried some tips i found earlier, but nothing works.
I have added a disabled input for the sum result. Any suggestion what method i can use here?
Here is the full code:
var data = {Food:[{id:1,name:"Fried Rice",price:1e4},{id:2,name:"Fried Noodle",price:9e3},{id:3,name:"Pancake",price:8500},{id:4,name:"French Fries",price:7500}],Drink:[{id:1,name:"Cola",price:4600},{id:2,name:"Orange Juice",price:5400},{id:3,name:"Mineral Water",price:3500},{id:4,name:"Coffee",price:5800}]};
function handleChange(e) {
var $row = e ? $(e).closest(".menu-position") : $('.menu-position')
var selectedCategory = $row.find('.category-select').val()
var $typeSelect = $row.find('.type-select')
var dataOptions = data[selectedCategory]
$typeSelect.html('')
dataOptions.forEach(function(option) {
var optionEle = document.createElement('option')
optionEle.value = option.id
optionEle.label = option.name
optionEle.setAttribute('data-price', option.price)
$typeSelect.append(optionEle)
})
}
handleChange()
$(".addRow").click(function () {
var $typeSelect = $(".type-select").clone()
var html = '<div class="row outer menu-position">';
html += '<div class="col-md-3">';
html += '<button type="button" class="btn btn-danger btn-lg delRow">Del</button>';
html += '</div>';
html += '<div class="col-md-3">';
html += '<select class="form-select form-select-lg mb-3 category-select cat" onChange="handleChange(this)">';
html += '<option value="Food">Food</option>';
html += '<option value="Drink">Drink</option>';
html += '</select>';
html += '</div>';
html += '<br>';
html += '<div class="col-md-3">';
html += '<select class="form-select form-select-lg mb-3 type-select type">' + $typeSelect.html() + '</select>';
html += '</div>';
html += '<div class="col-md-3">';
html += '<input type="number" class="form-control form-control-lg mb-3 qty" placeholder="Qty" min="0">';
html += '</div>';
html += '</div>';
$('.container-fluid').append(html);
});
$(document).on('click', '.delRow', function () {
$(this).closest('.row').remove();
$('.order').trigger('click')
});
$(document).ready(function () {
$('.order').click(function () {
var selectMenu = {};
$("select.type").each(function (i) {
selectMenu[i] = {}
var text = $(this).find("option:selected").attr('label');
var price = Number($(this).find("option:selected").data('price'));
var qty = Number($(this).closest(".row").find(".qty").val())
selectMenu[i] = {
"total": price * qty,
"itemname": text
}
})
$('.result tbody').html("");
$.each(selectMenu, function (index, data) {
$('.result tbody').append("<tr class='orders'><td>" + data.itemname + '</td><td>' + data.total + "</td></tr>");
})
});
});
button[type=submit] {
width: 50%;
margin-left: 25%;
margin-right: 25%;
}
button[type=button] {
font-size: 20px;
width: 50%;
margin-left: 25%;
margin-right: 25%;
}
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
<div class="container">
<div class="container-fluid text-center">
<h2 style="font-size:70px; font-family:Lucida Console;">MENU</h2>
<br>
<div class="row menu-position">
<div class="col-md-3">
<button type="button" class="btn btn-primary btn-lg addRow">Add</button>
</div>
<div class="col-md-3">
<select class="form-select form-select-lg mb-3 category-select cat" onChange='handleChange(this)'>
<option value="Food">Food</option>
<option value="Drink">Drink</option>
</select>
</div>
<br>
<div class="col-md-3">
<select class="form-select form-select-lg mb-3 type-select type"></select>
</div>
<div class="col-md-3">
<input type="number" class="form-control form-control-lg mb-3 qty" placeholder="Qty" min="0">
</div>
</div>
</div>
</div>
<br>
<button type="submit" class="btn btn-secondary order">Order</button>
<br>
<br>
<div class="result text-center">
<table class="table table-bordered">
<thead>
<tr>
<th style="width:50%">Item name</th>
<th style="width:50%">Price</th>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
<br>
<div class="totalPrice text-center">
<h4>Total Price</h4>
<input type="number" disabled> <!-- sum price result here -->
</div>
As you are already using each loop to show your trs you can declare some variable i.e total and then inside each loop just use total += parseInt(data.total) and then show same inside your input .
Demo Code :
var data = {
Food: [{
id: 1,
name: "Fried Rice",
price: 1e4
}, {
id: 2,
name: "Fried Noodle",
price: 9e3
}, {
id: 3,
name: "Pancake",
price: 8500
}, {
id: 4,
name: "French Fries",
price: 7500
}],
Drink: [{
id: 1,
name: "Cola",
price: 4600
}, {
id: 2,
name: "Orange Juice",
price: 5400
}, {
id: 3,
name: "Mineral Water",
price: 3500
}, {
id: 4,
name: "Coffee",
price: 5800
}]
};
function handleChange(e) {
var $row = e ? $(e).closest(".menu-position") : $('.menu-position')
var selectedCategory = $row.find('.category-select').val()
var $typeSelect = $row.find('.type-select')
var dataOptions = data[selectedCategory]
$typeSelect.html('')
dataOptions.forEach(function(option) {
var optionEle = document.createElement('option')
optionEle.value = option.id
optionEle.label = option.name
optionEle.setAttribute('data-price', option.price)
$typeSelect.append(optionEle)
})
}
handleChange()
$(".addRow").click(function() {
var $typeSelect = $(".type-select").clone()
var html = '<div class="row outer menu-position">';
html += '<div class="col-md-3">';
html += '<button type="button" class="btn btn-danger btn-lg delRow">Del</button>';
html += '</div>';
html += '<div class="col-md-3">';
html += '<select class="form-select form-select-lg mb-3 category-select cat" onChange="handleChange(this)">';
html += '<option value="Food">Food</option>';
html += '<option value="Drink">Drink</option>';
html += '</select>';
html += '</div>';
html += '<br>';
html += '<div class="col-md-3">';
html += '<select class="form-select form-select-lg mb-3 type-select type">' + $typeSelect.html() + '</select>';
html += '</div>';
html += '<div class="col-md-3">';
html += '<input type="number" class="form-control form-control-lg mb-3 qty" placeholder="Qty" min="0">';
html += '</div>';
html += '</div>';
$('.container-fluid').append(html);
});
$(document).on('click', '.delRow', function() {
$(this).closest('.row').remove();
$('.order').trigger('click')
});
$(document).ready(function() {
$('.order').click(function() {
var selectMenu = {};
$("select.type").each(function(i) {
selectMenu[i] = {}
var text = $(this).find("option:selected").attr('label');
var price = Number($(this).find("option:selected").data('price'));
var qty = Number($(this).closest(".row").find(".qty").val())
selectMenu[i] = {
"total": price * qty,
"itemname": text
}
})
$('.result tbody').html("");
var total = 0 //decalre this
$.each(selectMenu, function(index, data) {
$('.result tbody').append("<tr class='orders'><td>" + data.itemname + '</td><td>' + data.total + "</td></tr>");
total += parseInt(data.total); //sum total
})
$(".totalPrice input").val(total) //show inside inputs
});
});
button[type=submit] {
width: 50%;
margin-left: 25%;
margin-right: 25%;
}
button[type=button] {
font-size: 20px;
width: 50%;
margin-left: 25%;
margin-right: 25%;
}
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
<div class="container">
<div class="container-fluid text-center">
<h2 style="font-size:70px; font-family:Lucida Console;">MENU</h2>
<br>
<div class="row menu-position">
<div class="col-md-3">
<button type="button" class="btn btn-primary btn-lg addRow">Add</button>
</div>
<div class="col-md-3">
<select class="form-select form-select-lg mb-3 category-select cat" onChange='handleChange(this)'>
<option value="Food">Food</option>
<option value="Drink">Drink</option>
</select>
</div>
<br>
<div class="col-md-3">
<select class="form-select form-select-lg mb-3 type-select type"></select>
</div>
<div class="col-md-3">
<input type="number" class="form-control form-control-lg mb-3 qty" placeholder="Qty" min="0">
</div>
</div>
</div>
</div>
<br>
<button type="submit" class="btn btn-secondary order">Order</button>
<br>
<br>
<div class="result text-center">
<table class="table table-bordered">
<thead>
<tr>
<th style="width:50%">Item name</th>
<th style="width:50%">Price</th>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
<br>
<div class="totalPrice text-center">
<h4>Total Price</h4>
<input type="number" disabled>
<!-- sum price result here -->
</div>
I did not understand your question. But I think you want to sum all the price.
So I have made a little code for you. Hope it will work
let data= {Food:[{id:1,name:"Fried Rice",price:1e4},{id:2,name:"Fried Noodle",price:9e3},{id:3,name:"Pancake",price:8500},{id:4,name:"French Fries",price:7500}],Drink:[{id:1,name:"Cola",price:4600},{id:2,name:"Orange Juice",price:5400},{id:3,name:"Mineral Water",price:3500},{id:4,name:"Coffee",price:5800}]};
let keys = Object.keys(data)
console.log(keys)//["Food", "Drink"]
let price = 0
for (let i = 0; i < keys.length; i++) {
let items = data[keys[i]] //Access the values of the key
for (let j = 0; j < items.length; j++) {
console.log(items[j].price) //10000 ....(in loop)
price = price + items[j].price
}
}
console.log(price)//54300
I need to trigger the class "alert success" when the button is clicked in HTML,
The code is:
function appendText() {
var title = $("#title").val();
var content = $("#content").val();
var type = $("#type").val();
var markup = "<div>" + title + content + "</div>";
$(".alert success").append(markup);
$(".closebtn").append()
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p style="margin-top: 2%">
<select id="type">
<option value="success">success</option>
<option value="info">info</option>
<option value="warning">warning</option>
<option value="error">error</option>
</select>
<label for="title">title:</label>
<input type="text" value="title" id="title">
<label for="content">content:</label>
<input type="text" id="content" value="content" style="width: 50%">
<button onclick="appendText()">Add Notification</button>
</p>
I need to create dynamically the following HTML code when the button is clicked.
<div class="alert success">
<span class="closebtn">×</span>
<strong>Success!</strong> Indicates a successful or positive action.
</div>
Can you suggest the correct Jquery code for my need?
Here is working and simplified snippet.
Its appending the notification data and also the closebtn close button is working as well and deleting the clicked notification.
Just run snippet to see in action.
function appendText() {
var title = $("#title").val();
var content = $("#content").val();
var type = $("#type").val();
var markup = "<div class='results'><button class='closebtn' onclick='closeAlert(this)'>X</button> " + type + ' ' + title + ' ' + content + "</div>";
if (type === 'success') {
$('.messages').css({
"background-color": "green"
});
} else if (type === 'warning') {
$('.messages').css({
"background-color": "yellow"
});
} else if (type === 'error') {
$('.messages').css({
"background-color": "red"
});
} else if (type === 'info') {
$('.messages').css({
"background-color": "blue"
});
}
$(".messages").html(markup);
}
function closeAlert(_this) {
$(_this).parent().remove()
}
label,
button {
display: block;
}
.results {
display: flex;
padding: 5px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p style="margin-top: 2%">
<select id="type">
<option value="success">success</option>
<option value="info">info</option>
<option value="warning">warning</option>
<option value="error">error</option>
</select>
<label for="title">title:</label>
<input type="text" value="title" id="title">
<label for="content">content:</label>
<input type="text" id="content" value="content" style="width: 50%">
<button onclick="appendText()">Add Notification</button>
</p>
<div class="messages"></div>
function appendText() {
var title = $("#title").val();
var content = $("#content").val();
var type = $("#type").val();
var result = '<div>'
+ title + ' ' + content
+ '<div class="alert success">'
+ '<span class="closebtn">×</span>'
+ '<strong>Success!</strong> Indicates a successful or positive action.'
+ '</div>'
+ '</div>';
$('#result').append(result);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p style="margin-top: 2%">
<select id="type">
<option value="success">success</option>
<option value="info">info</option>
<option value="warning">warning</option>
<option value="error">error</option>
</select>
<label for="title">title:</label>
<input type="text" value="title" id="title">
<label for="content">content:</label>
<input type="text" id="content" value="content" style="width: 50%">
<button onclick="appendText()">Add Notification</button>
</p>
<div id="result"></div>
For HTML Tags or Content
var content = "Hello World";
$(".className").html(content);
Or
var content = "<b>Hello World</b>";
$(".className").html(content);
why can not my function register a text that is clicked, but must I enter it manually to calculate in total?
Namely, my idea is that by clicking on a product, it is displayed in the input field [284] of the product price, and when clicking on a checkbox option to increase the price and display it at the end of [388], the text menu can now only it is compiled if I enter a number manually in field 285. How can I do it?
function displayAbo(el) {
document.getElementById("contactFormFieldId_284").value = el.querySelector('.product__title').textContent+ " " +el.querySelector('.product__price').textContent;
}
var checkBoxes = document.getElementsByClassName('contactFormClass_checkbox');
var sum = 0,
inputField = document.getElementById('contactFormFieldId_284'),
finalInput = document.getElementById('contactFormFieldId_388');
Array.prototype.slice.call(checkBoxes).forEach( (checkBox) => {
checkBox.addEventListener('change', calculateTotal, false);
})
inputField.addEventListener('blur', calculateSumWithInput, false);
function calculateTotal(e) {
if(e.target.checked) {
sum += parseInt(e.target.value, 10);
} else {
sum -= parseInt(e.target.value, 10);
}
finalInput.value ="CHF "+ sum + ".–";
}
function calculateSumWithInput(e) {
var re = /\d+/;
var value = re.exec(e.target.value);
if(value && !isNaN(value) && Number(value) === parseInt(value, 10)) {
sum = parseInt(value, 10);
finalInput.value = sum;
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="product__item" onclick="displayAbo(this)" id="product-medium" tabindex="-1" role="radio" aria-checked="false" aria-describedby="medium-desc">
<div class="product__inner" id="medium-desc">
<h3 class="product__title">LEUWIN M</h3>
<ul class="product__features">
<li class="product__features-item">40 Mbit/s</li>
<li class="product__features-item"><img src="themes/zuerich/images/I.png" style="width: 100px; margin-right: 110px;"></li>
</ul>
<h4 class="product__price">CHF 39.–</h4>
</div>
</div>
<div class="contact row">
<label for="contactFormFieldId_284" style="color: #003664; font-size: 16px; font-weight: bold;">[[284_LABEL]]</label>
<input class="contactFormClass_text" id="contactFormFieldId_284" type="text" name="contactFormField_284" value="[[284_VALUE]]" readonly />
</div>
<div class="contact row">
<label for="contactFormFieldId_385">[[385_LABEL]]</label>
<input class="contactFormClass_checkbox" id="contactFormFieldId_385" type="checkbox" name="contactFormField_385" value="5" [[SELECTED_385]] />
</div>
<div class="contact row">
<label for="contactFormFieldId_386">[[386_LABEL]]</label>
<input class="contactFormClass_checkbox" id="contactFormFieldId_386" type="checkbox" name="contactFormField_386" value="15" [[SELECTED_386]] />
</div>
<div class="contact row">
<label for="contactFormFieldId_387">[[387_LABEL]]</label>
<input class="contactFormClass_checkbox" id="contactFormFieldId_387" type="checkbox" name="contactFormField_387" value="20" [[SELECTED_387]] />
</div>
<div class="contact row">
<label for="contactFormFieldId_388" style="color: #003664; font-size: 16px; font-weight: bold;">[[388_LABEL]]</label>
<input class="contactFormClass_text" id="contactFormFieldId_388" type="text" name="contactFormField_388" value="0" />
</div>
I have made 2 changes.
Changed your blur function to click
inputField.addEventListener('click', calculateSumWithInput, false);
Added click triggers in your functions
inputField.click();
function displayAbo(el) {
document.getElementById("contactFormFieldId_284").value = el.querySelector('.product__title').textContent + " " + el.querySelector('.product__price').textContent;
inputField.click();
}
var checkBoxes = document.getElementsByClassName('contactFormClass_checkbox');
var sum = 0,
inputField = document.getElementById('contactFormFieldId_284'),
finalInput = document.getElementById('contactFormFieldId_388');
Array.prototype.slice.call(checkBoxes).forEach((checkBox) => {
checkBox.addEventListener('change', calculateTotal, false);
})
inputField.addEventListener('click', calculateSumWithInput, false);
inputField.click();
function calculateTotal(e) {
if (e.target.checked) {
sum += parseInt(e.target.value, 10);
} else {
sum -= parseInt(e.target.value, 10);
}
finalInput.value = "CHF " + sum + ".–";
}
function calculateSumWithInput(e) {
var re = /\d+/;
var value = re.exec(e.target.value);
if (value && !isNaN(value) && Number(value) === parseInt(value, 10)) {
sum = parseInt(value, 10);
finalInput.value = "CHF " + sum + ".–";
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="product__item" onclick="displayAbo(this)" id="product-medium" tabindex="-1" role="radio" aria-checked="false" aria-describedby="medium-desc">
<div class="product__inner" id="medium-desc">
<h3 class="product__title">LEUWIN M</h3>
<ul class="product__features">
<li class="product__features-item">40 Mbit/s</li>
<li class="product__features-item"><img src="themes/zuerich/images/I.png" style="width: 100px; margin-right: 110px;"></li>
</ul>
<h4 class="product__price">CHF 39.–</h4>
</div>
</div>
<div class="contact row">
<label for="contactFormFieldId_284" style="color: #003664; font-size: 16px; font-weight: bold;">[[284_LABEL]]</label>
<input class="contactFormClass_text" id="contactFormFieldId_284" type="text" name="contactFormField_284" value="[[284_VALUE]]" readonly />
</div>
<div class="contact row">
<label for="contactFormFieldId_385">[[385_LABEL]]</label>
<input class="contactFormClass_checkbox" id="contactFormFieldId_385" type="checkbox" name="contactFormField_385" value="5" [[SELECTED_385]] />
</div>
<div class="contact row">
<label for="contactFormFieldId_386">[[386_LABEL]]</label>
<input class="contactFormClass_checkbox" id="contactFormFieldId_386" type="checkbox" name="contactFormField_386" value="15" [[SELECTED_386]] />
</div>
<div class="contact row">
<label for="contactFormFieldId_387">[[387_LABEL]]</label>
<input class="contactFormClass_checkbox" id="contactFormFieldId_387" type="checkbox" name="contactFormField_387" value="20" [[SELECTED_387]] />
</div>
<div class="contact row">
<label for="contactFormFieldId_388" style="color: #003664; font-size: 16px; font-weight: bold;">[[388_LABEL]]</label>
<input class="contactFormClass_text" id="contactFormFieldId_388" type="text" name="contactFormField_388" value="0" />
</div>
How can i add the "Div" Instead of
Tables & tr
I have tried many time with div instead of Table and tr
and failed
Im just about to create invoice calculation
if any one know about this please let me know
thank you
$(window).load(function(){
$(document).ready(function () {
// copy customer details to shipping
$('input.copy-input').on("change keyup paste", function () {
var thisID = $(this).attr('id');
$('input#' + thisID + "_ship").val($(this).val());
});
// add new product row on invoice
var cloned = $('#invoice_table tr:last').clone();
$(".add-row").click(function (e) {
e.preventDefault();
cloned.clone().appendTo('#invoice_table');
});
calculateTotal();
$('#invoice_table').on('change keyup paste', '.calculate', function() {
updateTotals(this);
calculateTotal();
});
function updateTotals(elem) {
var tr = $(elem).closest('tr'),
quantity = $('[name="invoice_product_qty[]"]', tr).val(),
price = $('[name="invoice_product_price[]"]', tr).val(),
percent = $('[name="invoice_product_discount[]"]', tr).val(),
subtotal = parseInt(quantity) * parseFloat(price);
if(percent && $.isNumeric(percent) && percent !== 0){
subtotal = subtotal - ((parseInt(percent) / 100) * subtotal);
}
$('.calculate-sub', tr).val(subtotal.toFixed(2));
}
function calculateTotal(){
var grandTotal = 0.0;
var totalQuantity = 0;
$('.calculate-sub').each(function(){
grandTotal += parseFloat($(this).val()) ;
});
$('.invoice-sub-total').text(parseFloat(grandTotal ).toFixed(2) );
}
});
});//]]>
$(window).load(function(){
$(document).ready(function () {
// copy customer details to shipping
$('input.copy-input').on("change keyup paste", function () {
var thisID = $(this).attr('id');
$('input#' + thisID + "_ship").val($(this).val());
});
// add new product row on invoice
var cloned = $('#invoice_table tr:last').clone();
$(".add-row").click(function (e) {
e.preventDefault();
cloned.clone().appendTo('#invoice_table');
});
calculateTotal();
$('#invoice_table').on('change keyup paste', '.calculate', function() {
updateTotals(this);
calculateTotal();
});
function updateTotals(elem) {
var tr = $(elem).closest('tr'),
quantity = $('[name="invoice_product_qty[]"]', tr).val(),
price = $('[name="invoice_product_price[]"]', tr).val(),
percent = $('[name="invoice_product_discount[]"]', tr).val(),
subtotal = parseInt(quantity) * parseFloat(price);
if(percent && $.isNumeric(percent) && percent !== 0){
subtotal = subtotal - ((parseInt(percent) / 100) * subtotal);
}
$('.calculate-sub', tr).val(subtotal.toFixed(2));
}
function calculateTotal(){
var grandTotal = 0.0;
var totalQuantity = 0;
$('.calculate-sub').each(function(){
grandTotal += parseFloat($(this).val()) ;
});
$('.invoice-sub-total').text(parseFloat(grandTotal ).toFixed(2) );
}
});
});//]]>
<style type="text/css">
body {
padding: 2em 0;
}
.panel-body {
padding: 15px 15px 0 15px;
}
}
.float-left {
float: left !important;
}
.float-right {
float: right !important;
}
.margin-bottom {
margin-bottom: 1em;
}
.margin-top {
margin-top: 1em;
}
/* Form validation */
#response {
margin: 0 1em 1em 1em;
}
</style>
<head><script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
</head>
<body>
<h1>Create invoice</h1>
<hr>
<div class="row">
<div class="col-xs-6 text-right">
<table class="table table-bordered" id="invoice_table">
<tbody>
<tr>
<td>
<div class=" form-group">
<select name="invoice_product[]">
<option>Versa Table - Wildberry</option><option>Versa Table - Aubergine</option><option>Versa Table - Blue Jazz</option><option>Versa Table - Tundra Spring</option> </select>
</div>
</td>
<td>
<div class=" form-group form-group-sm">
<input class="form-control calculate" name="invoice_product_qty[]" value="1" type="text">
</div>
</td>
<td>
<div class="input-group input-group-sm">
<span class="input-group-addon">£</span>
<input class="form-control calculate" name="invoice_product_price[]" value="0.00" aria-describedby="sizing-addon1" type="text">
</div>
</td>
<td>
<div class=" form-group form-group-sm">
<input class="form-control calculate" name="invoice_product_discount[]" placeholder="Enter % or value (ex: 10% or 10.50)" type="text">
</div>
</td>
<td><div class=" form-group form-group-sm">
<div class="col-lg-2">
<input type="text" name="sub_total" class="form-control calculate-sub" id="subtotal" value="0.00" aria-describedby="sizing-addon1" disabled>
</div>
</td>
</tr>
</tbody>
</table>
<div class="row text-right">
<div class="col-xs-2 col-xs-offset-8">
<p>
<strong>
Sub Total: <br>
TAX/VAT: <br>
Total: <br>
</strong>
</p>
</div>
<div class="col-xs-2">
<strong>
£<span class="invoice-sub-total">20.00</span> <br>
£<span class="invoice-vat">0.00</span> <br>
£<span class="invoice-total">0.00</span> <br>
</strong>
</div>
</div>