How to apply condition on document.getElementsByClassName - javascript

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>

Related

How to trigger the class and append the content in jquery?

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);

Is it possible to focus on textarea after selecting option?

After adding text inside textarea i would like to focus caret just after this input. Unfortunately I can't make function focus() to be called. Although when I use focus() on click it works perfectly
Here is my function:
function append_textarea(textarea, select, div_for_select) {
$(textarea).on('keyup paste cut mouseup', function (event) {
var contentHeight = $(this).textareaHelper('height');
$(this).height(contentHeight);
var obj = $(this).textareaHelper('caretPos');
var left = obj.left + 15;
var top = obj.top + 50;
if (event.which === 219) {
$(div_for_select).attr('style', 'top: ' + top + 'px;' + ' left: ' + left + 'px;').fadeIn();
openDropdown(select);
} else if (event.which === 221) {
$(div_for_select).fadeOut('slow');
}
});
$(div_for_select).on('keydown click', function (event) {
if (event.which === 13 || event.which === 1) {
var $txt = $(textarea);
var caretPos = $txt[0].selectionStart;
var textAreaTxt = $txt.val();
var txtToAdd = $(select).val();
$txt.val(textAreaTxt.substring(0, caretPos) + txtToAdd + textAreaTxt.substring(caretPos)).focus();
$(this).fadeOut('slow');
}
});
$(textarea).keyup();
function openDropdown(elementId) {
function down() {
var pos = $(this).offset(); // remember position
var len = $(this).find("option").length;
if (len > 20) {
len = 20;
}
$(this).css("position", "absolute");
$(this).css("zIndex", 9999);
$(this).offset(pos); // reset position
$(this).attr("size", len); // open dropdown
$(this).unbind("focus", down);
$(this).trigger('focus');
}
function up() {
$(this).css("position", "static");
$(this).attr("size", "1"); // close dropdown
$(this).unbind("change", up);
$(this).trigger('focus')
}
$(elementId).focus(down).blur(up).focus();
}
}
append_textarea('#example', '#select', '.tail');
$('#select').on('click', function () {
$('#example').focus();
});
$('#click').on('click', function () {
$('#example').focus();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<style>
.tail {
position: absolute;
}
textarea {
min-width: 250px;
min-height: 100px;
}
</style>
<!-- #MAIN PANEL -->
<div id="main" role="main">
<!-- RIBBON -->
<div id="ribbon">
<!-- breadcrumb -->
<ol class="breadcrumb">
<li>Home</li>
</ol>
</div>
<!-- col -->
<div class="col-xs-12 col-sm-7 col-md-7 col-lg-4">
<h1 class="page-title txt-color-blueDark"></h1>
<div class="clearfix"></div>
<textarea id="example"></textarea>
<div class="tail" hidden>
<select id="select">
<option style="display: none;">Please select one</option>
<option value="USER_NAME}">First and Last Name</option>
<option value="WO_NO}">Work Order Number</option>
<option value="PROD}">Product Name and Size</option>
<option value="PROJECT}">Project Name</option>
<option value="MACHINE}">Machine Name</option>
</select>
</div>
<div>
<input type="button" value="CLICK ME!" id="click">
</div>
</div>
</div>
<script src="https://rawgit.com/Codecademy/textarea-helper/master/textarea-helper.js"></script>

I cannot figure out why this simple Javascript will not work. Can anyone shed some light?

I am trying to make a travel calculator, here is the HTML, which all works fine with the CSS styling I have attached to it. No issues here.
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge"/>
<title>Travel Calculator 2.0</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css"/>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<link rel="stylesheet" type="text/css" href="styles.css"/>
</head>
<body>
<div class="container-fluid">
<div id ="travel_calculator" class="row row-eq-height">
<div id ="common_and_results" class="col-sm-4 order-sm-4 pb-5 pt-3">
<div id ="results" class="card mb-3">
<img src="https://via.placeholder.com/1920x1080" alt="placeholder" class="card-img">
<div class="card-img-overlay">
<h1 class="card-title text-white h2">Change Options</h1>
</div>
<div class="col-12">
<div class="card bg-info mb-3">
<div class="form-group card-body">
<label class="h6" for="pay_rate">Pay Rate (assuming 8hr/day)</label>
<div id="pay-rate-group" class="input-group">
<div class="input-group-prepend">
<span class="input-group-text">
<i class="fa fa-money"></i>
</span>
<input class="form-control" name="pay_rate" type="number"
id="pay_rate" max="80" min="8" step="1" value="15">
</div>
</div>
</div>
<div class="form-group card-body">
<label class="h6" for="travelers">Travelers</label>
<div id="travelers-group" class="input-group">
<div class="input-group-prepend">
<span class="input-group-text">
<i class="fa fa-user" aria-hidden="true"></i>
</span>
<input class="form-control" name="travelers" type="number"
id="travelers" max="5" min="1" step="1" value="1">
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div id="car" class="col-sm-4 order-sm-1 pb-5 pt-3">
<div class="card mb-3">
<img src="images/pexels-photo-car.jpg" alt="car photo" class="card-img">
<div class="card-img-overlay">
<h1 class="card-title text-white h2">By Car</h1>
</div>
</div>
<div class="col-12">
<div class="card bg-info mb-3">
<div class="form-group card-body">
<label class="h6" for="distance">Distance</label>
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text">
<i class="fa fa-car" aria-hidden="true"></i>
</span>
<input class="form-control" name="distance" type="number"
id="distance" max="5000" min="50" step="10" value="500">
</div>
</div>
</div>
<div class="form-group card-body">
<label class="h6" for="mpg">MPG</label>
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text">
<i class="fa fa-tint" aria-hidden="true"></i>
</span>
<input class="form-control" name="mpg" type="number"
id="mpg" max="100" min="10" step="1" value="23">
</div>
</div>
</div>
<div class="form-group card-body">
<label class="h6" for="ppg">PPG</label>
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text">
<i class="fa fa-credit-card" aria-hidden="true"></i>
</span>
<input class="form-control" name="ppg" type="number"
id="ppg" max="20" min=".10" step=".10" value="2.50">
</div>
</div>
</div>
<div class="form-group card-body">
<label class="h6" for="hotel">Hotel</label>
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text">
<i class="fa fa-bed"></i>
</span>
<select class="custom-select form-control" name="hotel" id="hotel">
<option value="100">Economy</option>
<option value="200">Business</option>
<option value="300">Luxury</option>
</select>
</div>
</div>
</div>
</div>
</div>
</div>
<div id="plane" class="col-sm-4 order-sm-1 pb-5 pt-3">
<div class="card mb-3">
<img src="images/pexels-photo-plane.jpg" alt="plane photo" class="card-img">
<div class="card-img-overlay">
<h1 class="card-title text-white h2">By Air</h1>
</div>
</div>
<div class="col-12">
<div class="card bg-info mb-3">
<div class="form-group card-body">
<label class="h6" for="ticket">Ticket</label>
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text">
<i class="fa fa-credit-card"></i>
</span>
<input class="form-control" name="ticket" type="number"
id="ticket" max="3000" min="50" step="50" value="500">
</div>
</div>
</div>
<div class="form-group card-body">
<label class="h6" for="bags">Bags</label>
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text">
<i class="fa fa-briefcase" aria-hidden="true"></i>
</span>
<input class="form-control" name="checked_bags" type="number"
id="checked_bags" max="2" min="1" step="1" value="1">
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div id="update-row" class="row">
<div id="update-column" class="col-12">
<button id="update_button" class="btn btn-primary btn-block">Calculate</button>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
<script src="travel-calculator.js"></script>
</body>
</html>
The JavaScript is supposed to display a car or plane photo on top of the placeholder in the "change options" column alongside attached prices and instructions of whether to take a car or plane. But when I press the calculate button, literally nothing happens.
$(function () {
"use strict";
var pay_rate = 0;
var travelers = 0;
var distance = 0;
var hotel = 0;
var MAX_MILES = 300; // assume driving only 300 mi/day
var WORK_HOURS = 8; // assume 8 hours of work/day
function getCommonCosts() {
pay_rate = Number($("#pay_rate").val());
console.log("pay_rate " + pay_rate);
travelers = Number($("#travelers").val());
console.log("travelers " + travelers);
}
function getCarCosts() {
var mpg = Number($("#mpg").val());
console.log("mpg " + mpg);
var ppg = Number($("#ppg").val());
console.log("ppg " + ppg);
distance = Number($("#distance").val());
console.log("distance " + distance);
hotel = Number($("#hotel").val());
console.log("hotel " + hotel);
var gallons = distance / mpg;
console.log("gallons " + gallons);
var mileage_cost = gallons * ppg;
console.log("mileage_cost " + mileage_cost);
var by_car_days = Math.ceil(distance / MAX_MILES);
console.log("by_car_days " + by_car_days);
var by_car_hotel = Math.floor(by_car_days) * hotel;
console.log("by_car_hotel " + by_car_hotel);
var by_car_pay =
Math.ceil(by_car_days) * WORK_HOURS * pay_rate * travelers;
console.log("by_car_pay " + by_car_pay);
var total = mileage_cost + by_car_hotel + by_car_pay;
console.log("(car) total " + total);
return total;
}
function getFlightCosts() {
var cost_per_bag = 50;
console.log("cost_per_bag " + cost_per_bag);
var flight_cost = Number($("#flight_cost").val());
console.log("flight_cost " + flight_cost);
var checked_bags = Number($("#checked_bags").val());
console.log("checked_bags " + checked_bags);
var by_flight_pay = WORK_HOURS * pay_rate * travelers;
console.log("by_flight_pay " + by_flight_pay);
var total = (flight_cost * travelers) +
(checked_bags * cost_per_bag) + by_flight_pay;
console.log("(plane) total " + total);
return total;
}
function showResult(cost1, cost2) {
var result_text = "";
if (cost1 < cost2) {
$("results img").attr(
"src",
"images/pexels-photo-car.jpg"
);
result_text = "Road Trip!";
} else {
$("results img").attr(
"src",
"images/pexels-photo-plane.jpg"
);
result_text = "Book a Flight!";
}
result_text = "<br/>";
cost1 = Math.round(cost1 * 100) / 100;
cost2 = Math.round(cost2 * 100) / 100;
result_text += "Car: $" + cost1 + "<br/>";
result_text += "Flight: $" + cost2 + "<br/>";
$("results h1").html(result_text);
}
function updateResults() {
getCommonCosts();
var car_costs = getCarCosts() || 0;
var flight_costs = getFlightCosts || 0;
showResult(car_costs, flight_costs);
}
$("update_button").focus();
$("update_button").click(function () {
updateResults();
});
});
Post-edit javascript:
$(function () {
"use strict";
var pay_rate = 0;
var travelers = 0;
var distance = 0;
var hotel = 0;
var MAX_MILES = 300; // assume driving only 300 mi/day
var WORK_HOURS = 8; // assume 8 hours of work/day
function getCommonCosts() {
pay_rate = Number($("#pay_rate").val());
console.log("pay_rate " + pay_rate);
travelers = Number($("#travelers").val());
console.log("travelers " + travelers);
}
function getCarCosts() {
var mpg = Number($("#mpg").val());
console.log("mpg " + mpg);
var ppg = Number($("#ppg").val());
console.log("ppg " + ppg);
distance = Number($("#distance").val());
console.log("distance " + distance);
hotel = Number($("#hotel").val());
console.log("hotel " + hotel);
var gallons = distance / mpg;
console.log("gallons " + gallons);
var mileage_cost = gallons * ppg;
console.log("mileage_cost " + mileage_cost);
var by_car_days = Math.ceil(distance / MAX_MILES);
console.log("by_car_days " + by_car_days);
var by_car_hotel = Math.floor(by_car_days) * hotel;
console.log("by_car_hotel " + by_car_hotel);
var by_car_pay =
Math.ceil(by_car_days) * WORK_HOURS * pay_rate * travelers;
console.log("by_car_pay " + by_car_pay);
var total = mileage_cost + by_car_hotel + by_car_pay;
console.log("(car) total " + total);
return total;
}
function getFlightCosts() {
var cost_per_bag = 50;
console.log("cost_per_bag " + cost_per_bag);
var flight_cost = Number($("#flight_cost").val());
console.log("flight_cost " + flight_cost);
var checked_bags = Number($("#checked_bags").val());
console.log("checked_bags " + checked_bags);
var by_flight_pay = WORK_HOURS * pay_rate * travelers;
console.log("by_flight_pay " + by_flight_pay);
var total = (flight_cost * travelers) +
(checked_bags * cost_per_bag) + by_flight_pay;
console.log("(plane) total " + total);
return total;
}
function showResult(cost1, cost2) {
var result_text = "";
if (cost1 < cost2) {
$("#results img").attr(
"src",
"images/pexels-photo-car.jpg"
);
result_text = "Road Trip!";
} else {
$("#results img").attr(
"src",
"images/pexels-photo-plane.jpg"
);
result_text = "Book a Flight!";
}
result_text = "<br/>";
cost1 = Math.round(cost1 * 100) / 100;
cost2 = Math.round(cost2 * 100) / 100;
result_text += "Car: $" + cost1 + "<br/>";
result_text += "Flight: $" + cost2 + "<br/>";
$("results h1").html(result_text);
}
function updateResults() {
getCommonCosts();
var car_costs = getCarCosts() || 0;
var flight_costs = getFlightCosts() || 0;
showResult(car_costs, flight_costs);
}
$("#update_button").focus();
$("#update_button").click(function () {
updateResults();
});
});
This line:
$("results img")
This is not targeting an element. You need the pound sign to target that ID:
$("#results img")
So it should be:
$("#results img").attr(
"src",
"images/pexels-photo-car.jpg"
);
Please note, your listeners are also not targeting by ID. They all need to prefix with # for ID targeting, or . for class
Also, I think you have a typo:
var flight_costs = getFlightCosts || 0;
should probably be
var flight_costs = getFlightCosts() || 0;
But ultimately, your console will guide you through issues better than an eyeball audit. From a glance, those 2 things are going to be problematic. I can update this answer if more insight is posted after these are fixed.

Dynamically select / unselect items in event and get data attributes

I have 5 circles to click. User can select only one. My problem is that I can't deselect previous circle and remove its data-value from variable.
How can I handle it?
HTML
<div class="question">
<h3>' + test + '</h3>
<div class="row" style="padding-top:50px;">
<div class="col-xl-4 col-lg-3 col-md-2 col-sm-2 col-xs-3 text-center"> <span>Całkowicie nietrafnie mnie opisuje</span> </div>
<div class="col-xl-4 col-lg-6 col-md-8 col-sm-8 col-xs-6 text-center">
<div class="circles">
<div class="numberCircle" data-value="1">1</div>
<div class="numberCircle" data-value="2">2</div>
<div class="numberCircle" data-value="3">3</div>
<div class="numberCircle" data-value="4">4</div>
<div class="numberCircle" data-value="5">5</div>
</div>
</div>
<div class="col-xl-4 col-lg-3 col-md-2 col-sm-2 col-xs-3 text-center"><span>całkowicie trafnie mnie opisuje</span></div>
</div>
</div>
JS
pinEventAction = function (e) {
var progressBar = document.querySelector('#progressBar .bar');
var circles = document.querySelectorAll('.question .circles .clicked');
if (e.target.hasAttribute('data-value')) {
values += Number(e.target.getAttribute('data-value'));
e.target.className += ' clicked';
e.target.parentNode.className += ' checked';
width += 2;
progressBar.style.width = width + '%';
}
if (e.target.classList.contains('clicked')) {
e.target.classList.remove('clicked')
}
console.log('score: ' + values);
};
handleClickAndProgressBar = function () {
var progressBar = document.querySelector('#progressBar .bar');
var circles = document.querySelectorAll('.question .circles');
for (var i = 0; i < circles.length; i++) {
circles[i].addEventListener('click', pinEventAction);
}
};
No need to add an eventListener on each circle, you can add an eventListener to an ancestor node instead. By using event.target property, you can determine which node was clicked. Read on Event Delegation for details.
The behavior desired for the circles is like a group of radio buttons that share the same name attribute (only one can be checked). I changed the circles into a radio/label pair then wrapped them into a <fieldset> and a <form>. By doing this, saves you from writing code for the behavior previously mentioned.
This demo does the following:
Allows only one active circle
Allows toggling circles on/off
Updates value according to what is selected/unselected
Displays the value
Demo
var form = document.forms[0];
form.addEventListener('click', circle, false);
function circle(e) {
if (e.target !== e.currentTarget) {
var val = this.elements.view;
var tgt = e.target;
if (tgt.tagName === 'FIELDSET') {
return;
}
if (tgt.classList.contains('act')) {
tgt.classList.remove('act');
val.value = 0;
} else if (!tgt.classList.contains('act')) {
tgt.classList.add('act');
val.value = tgt.value;
}
} else {
if (val.value === undefined) {
val.value = 0;
}
return false;
}
e.stopPropagation();
}
.rad {
display: none
}
.l {
background: black;
color: gold;
border-radius: 50%;
width: 24px;
height: 24px;
cursor: pointer;
margin: 0 auto;
padding-top: 3px;
display: block;
}
.rad:checked+label.l.act {
color: cyan
}
.rad:checked+label.l.act::before {
content: '<'
}
.rad:checked+label.l.act::after {
content: '>'
}
#view {
color: tomato;
font-weight: 900
}
<link href='https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css' rel='stylesheet'>
<div class="question">
<h3>' + test + '</h3>
<div class="row" style="padding-top:50px;">
<div class="col-xs-3 text-center"> <span>Całkowicie nietrafnie mnie opisuje</span> </div>
<form class="col-xs-6 text-center">
<output id='view'>0</output>
<fieldset class="circles">
<input id='rad1' class='rad' name='rad' type='radio' value="1">
<label class="l" for='rad1'>1</label>
<input id='rad2' class='rad' name='rad' type='radio' value="2">
<label class="l" for='rad2'>2</label>
<input id='rad3' class='rad' name='rad' type='radio' value="3">
<label class="l" for='rad3'>3</label>
<input id='rad4' class='rad' name='rad' type='radio' value="4">
<label class="l" for='rad4'>4</label>
<input id='rad5' class='rad' name='rad' type='radio' value="5">
<label class="l" for='rad5'>5</label>
</fieldset>
</form>
<div class="col-xs-3 text-center"><span>całkowicie trafnie mnie opisuje</span></div>
</div>
</div>

I can't seem to get my code to work

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>

Categories