Change count JavaScript function - javascript

Currently, this function seems to count all the way to the higher value. I want it to simply count to the lower value of 30.
This is the script:
$(".circleStatsItemBox").each(function() {
var value = $(this).find(".value > .number").html();
var unit = $(this).find(".value > .unit").html();
var percent = $(this).find("input").val() / 100;
countSpeed = 2300 * percent;
endValue = value;
$(this).find(".count > .unit").html(unit);
$(this).find(".count > .number").countTo({
from: 0,
to: endValue,
speed: countSpeed,
refreshInterval: 50
});
//$(this).find(".count").html(value*percent + unit);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.rawgit.com/mhuggins/jquery-countTo/master/jquery.countTo.js"></script>
<div class="circleStatsItemBox yellow">
<div class="header">Levels of Interest</div>
<span class="percent">% Increase</span>
<div class="circleStat">
<input value="25" class="whiteCircle" type="text">
</div>
<div class="footer"><span class="count">
<span class="number">30</span>
<span class="unit">Before</span>
</span> <span class="sep"> / </span>
<span class="value">
<span class="number">40</span>
<span class="unit"> During</span>
</span>
</div>
</div>

You need to change a selector in the JavaScript code.
var value = $(this).find(".count > .number").html();
$(".circleStatsItemBox").each(function() {
var value = $(this).find(".count > .number").html();
var unit = $(this).find(".value > .unit").html();
var percent = $(this).find("input").val() / 100;
countSpeed = 2300 * percent;
endValue = value;
$(this).find(".count > .unit").html(unit);
$(this).find(".count > .number").countTo({
from: 0,
to: endValue,
speed: countSpeed,
refreshInterval: 50
});
//$(this).find(".count").html(value*percent + unit);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.rawgit.com/mhuggins/jquery-countTo/master/jquery.countTo.js"></script>
<div class="circleStatsItemBox yellow">
<div class="header">Levels of Interest</div>
<span class="percent">% Increase</span>
<div class="circleStat">
<input value="25" class="whiteCircle" type="text">
</div>
<div class="footer">
<span class="count">
<span class="number">30</span>
<span class="unit">Before</span>
</span>
<span class="sep"> / </span>
<span class="value">
<span class="number">40</span>
<span class="unit"> During</span>
</span>
</div>
</div>

Related

Combined total for multiple Sliders (Bootstrap v4 & jQuery)

I'm trying to implement a page with 3 sliders. The combined total of all 3 sliders should never go over 100%.
The page uses the Bootstrap 4 framework and jQuery 3.6.2
These is where I struggle:
The combined value of all three sliders should never be over 100%. Increasing one slider should decrease the other two values and vice versa.
Here is what I have done so far:
HTML
<div id="sliders">
<div class="row">
<label for="Focus1" class="form-label">Slider 1</label>
</div>
<div class="row">
<input id="sl1" type="text" data-slider-min="0" data-slider-max="100" data-slider-step="1" data-slider-value="34" data-value="34" value="34" style="display: none;">
<span id="sl1CurrentSliderValLabel"> <span class="value" id="sl1SliderVal">34</span>%</span>
</div>
<div class="row">
<label for="Focus2" class="form-label">Slider 2</label>
</div>
<div class="row">
<input id="sl2" type="text" data-slider-min="0" data-slider-max="100" data-slider-step="1" data-slider-value="33" data-value="33" value="33" style="display: none;"/>
<span id="sl2CurrentSliderValLabel"> <span class="value" id="sl2SliderVal">33</span>%</span>
</div>
<div class="row">
<label for="Focus3" class="form-label">Slider 3</label>
</div>
<div class="row">
<input id="sl3" type="text" data-slider-min="0" data-slider-max="100" data-slider-step="1" data-slider-value="33" data-value="33" value="33" style="display: none;"/>
<span id="sl3CurrentSliderValLabel"> <span class="value" id="sl3SliderVal">33</span>%</span>
</div>
</div>
JS
`
<script>
$(document).ready(function() {
$('.tooltip').tooltip();
/* Slider 1 */
$("#sl1").slider();
$("#sl1").on('slide', function(slideEvt) {
$("#sl1SliderVal").text(slideEvt.value);
});
/* Slider 2 */
$("#sl2").slider();
$("#sl2").on('slide', function(slideEvt) {
$("#sl2SliderVal").text(slideEvt.value);
});
/* Slider 3 */
$("#sl3").slider();
$("#sl3").on('slide', function(slideEvt) {
$("#sl3SliderVal").text(slideEvt.value);
});
});
/* Start Slider Logic */
var sliders = $("#sliders .slider");
var availableTotal = 100;
sliders.each(function() {
var init_value = parseInt($(this).text());
$(this).siblings('.value').text(init_value);
$(this).empty().slider({
value: init_value,
min: 0,
max: availableTotal,
range: "max",
step: 2,
animate: 0,
slide: function(event, ui) {
// Update display to current value
$(this).siblings('.value').text(ui.value);
// Get current total
var total = 0;
sliders.not(this).each(function() {
total += $(this).slider("option", "value");
});
total += ui.value;
var delta = availableTotal - total;
// Update each slider
sliders.not(this).each(function() {
var t = $(this),
value = t.slider("option", "value");
var new_value = value + (delta/2);
if (new_value < 0 || ui.value == 100)
new_value = 0;
if (new_value > 100)
new_value = 100;
t.siblings('.value').text(new_value);
t.slider('value', new_value);
});
}
});
});
</script>`
CSS
<link href="../css/bootstrap.min.css" rel="stylesheet">
<link href="../css/bootstrap-slider.css" rel="stylesheet">
Thanks a lot for your help!
The main problem was to use the correct API call at the right time.
This is the correct code to make the sliders work as intended:
JS
`
<script>
$(document).ready(function() {
$('.tooltip').tooltip();
var sliders = $("#sliders .slider");
var availableTotal = 100;
sliders.each(function() {
var init_value = parseInt(this.value);
$(this).siblings('.value').text(init_value);
$(this).empty().slider({
value: init_value,
min: 0,
max: availableTotal,
range: false,
step: 2,
animate: 0
});
$(this).on( "slide", function( event ) {
var slVal = parseInt($(this).val());
// Update display to current value
$(this).siblings('.value').text(slVal);
// Get current total
var total = 0;
sliders.not(this).each(function() {
total += parseInt($(this).val());
});
// Need to do this because apparently jQ UI
// does not update value until this event completes
total += slVal;
var delta = availableTotal - total;
// Update each slider
sliders.not(this).each(function() {
var t = $(this),
value = parseInt(t.slider('getValue'));
var new_value = parseInt(value + (delta/2));
if (new_value < 0 || slVal == 100)
new_value = 0;
if (new_value > 100)
new_value = 100;
t.siblings('.value').text(new_value);
t.slider('setValue',new_value);
});} );
});
});
</script>`
HTML
<div id="sliders">
<div class="row g-6">
<label for="Focus1" class="form-label">Slider 1</label>
</div>
<div class="row g-6">
<input class="slider" id="sl1" type="text" data-slider-min="0" data-slider-max="100" data-slider-step="1" data-slider-value="34" data-value="34" value="34" style="display: none;">
<span class="value" id="sl1SliderVal">34</span><span id="sl1CurrentSliderValLabel">%</span>
</div>
<div class="row g-6">
<label for="Focus2" class="form-label">Slider 2</label>
</div>
<div class="row g-6">
<input class="slider" id="sl2" type="text" data-slider-min="0" data-slider-max="100" data-slider-step="1" data-slider-value="33" data-value="33" value="33" style="display: none;"/>
<span class="value" id="sl2SliderVal">33</span><span id="sl2CurrentSliderValLabel">%</span>
</div>
<div class="row g-6">
<label for="Focus3" class="form-label">Slider 3</label>
</div>
<div class="row g-6">
<input class="slider" id="sl3" type="text" data-slider-min="0" data-slider-max="100" data-slider-step="1" data-slider-value="33" data-value="33" value="33" style="display: none;"/>
<span class="value" id="sl3SliderVal">33</span><span id="sl3CurrentSliderValLabel">%</span>
</div>
</div>
The CSS section from the question is unchanged.

Trying to calculate discount from two spans

I have this structure:
<div class="gs-item-price">
<span class="gs-old-price">5,00</span><br>
<span class="gs-new-price">1,00</span><br>
</div>
<br>
<span class="value1"></span> %
<br>
<br>
<div class="gs-item-price">
<span class="gs-old-price">10,00</span><br>
<span class="gs-new-price">5,00</span><br>
</div>
<br>
<span class="value1"></span> %
I need to calculate and visualize the discount percentage.
I have written the following code:
var OldPrice=$('.gs-old-price').html().replace(/,/g,'.');
var NewPrice=$('.gs-new-price').html().replace(/,/g,'.');
var oldPriceNum= parseFloat(OldPrice);
var newPriceNum= parseFloat(NewPrice);
var percent= oldPriceNum - newPriceNum;
var percent1= percent/oldPriceNum;
var percent2=percent1*100;
var finalPercent=parseFloat(percent2).toFixed(0);
document.querySelector('.value1').innerHTML = finalPercent;
That visualize only the first value of the percentage.
How can I go through all the divs and get the right percentage? All help will be good
I moved both <span class="value1"></span> % to the appropriate <div class="gs-item-price"> and then I called each. I also changed placing finalPercent. See the snippet:
$('.gs-item-price').each(function() {
var OldPrice=$(this).find('.gs-old-price').html().replace(/,/g,'.');
var NewPrice=$(this).find('.gs-new-price').html().replace(/,/g,'.');
var oldPriceNum= parseFloat(OldPrice);
var newPriceNum= parseFloat(NewPrice);
var percent= oldPriceNum - newPriceNum;
var percent1= percent/oldPriceNum;
var percent2=percent1*100;
var finalPercent=parseFloat(percent2).toFixed(0);
$(this).find('.value1').html(finalPercent)
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="gs-item-price">
<span class="gs-old-price">5,00</span><br>
<span class="gs-new-price">1,00</span><br>
<br>
<span class="value1"></span> %
<br>
</div>
<br>
<div class="gs-item-price">
<span class="gs-old-price">10,00</span><br>
<span class="gs-new-price">5,00</span><br>
<br>
<span class="value1"></span> %
</div>

JavaScript unsure how to get querySelectorAll() to connect to div class? [duplicate]

When I click on the checkbox at the top, it puts a '0' in the total box, so I know that it is connected correctly, however I think there is a problem in the logic in the loop. One of the elements in html looks like this.
const form = document.getElementById('bookingForm');
const total = document.getElementById('total');
const checkboxes = document.querySelectorAll('input[data-price][type=checkbox]');
const cbamount = checkboxes.length;
document.getElementsByName('event[]')[0].onclick = function() {
totalPrice()
};
function totalPrice() {
let totalprice = 0;
for (let i = 0; i < cbamount; i++) {
const box = checkboxes[i];
if (box.checked) {
box.dataset.price = totalprice + box.dataset.price;
} //if
} //for
document.getElementsByName("total")[0].value = totalprice;
}
<span class="eventTitle">Carmen </span>
<span class="eventStartDate">2020</span>
<span class="eventEndDate">2020</span>
<span class="catDesc">T</span>
<span class="venueName">Mill </span>
<span class="eventPrice">3</span>
<span class="chosen"><input type="checkbox" name="event[]" value="11" data-price="35.00"></span>
<section id="Cost">
<h3>Total</h3>
Total <input type="text" name="total" size="20" readonly="">
</section>
You have no total in the code you provided.
I would personally use ID when only having one element and if more, use relative addressing and/or delegation
const form = document.getElementById('booking');
const total = document.getElementById('total');
document.getElementById("booking").addEventListener("click", function(e) {
if (e.target.name === "event[]") {
let totalprice = 0;
[...document.querySelectorAll('input[data-price][type=checkbox]')].forEach(function(box) {
if (box.checked) {
totalprice += +box.dataset.price;
} //if
})
document.querySelector("[name=total]").value = totalprice.toFixed(2);
}
})
<form id="booking" method="get">
<section id="book">
<h2>Select Events</h2>
<div class="item">
<span class="eventTitle">Carmen </span>
<span class="eventStartDate">2020</span>
<span class="eventEndDate">2020</span>
<span class="catDesc">T</span>
<span class="venueName">Mill </span>
<span class="eventPrice">3</span>
<span class="chosen"><input name="event[]" type="checkbox" value="11" data-price="35.00"></span>
</div>
<div class="item">
<span class="eventTitle">Ash</span>
<span class="eventStartDate">202</span>
<span class="eventEnd">2020-12-31</span>
<span class="catD">Exhib</span>
<span class="venueNa">The Biy</span>
<span class="eventPr">0.00</span>
<span class="chosen"><input type="checkbox" name="event[]" value="17" data-price="10.00"></span>
</div>
</section>
<section id="Cost">
<h3>Total</h3>
Total <input type="text" name="total" size="20" readonly="">
</section>
</form>

Get total price added up with jquery

Newbie on JS and got really stuck.
I have a plus and a minus button that adds up products. But I need that the result of this total price to adds up accordingly. And some of the products can only be bought with multiples of 2, 5 or 10.
I have here my html with 2 of my products. One that can only be sold with multiples of 5 and the other, multiple of 10.
<!-- Product #6 -->
<div class="item">
<div class="buttons">
<span class="delete-btn"></span>
<span class="like-btn"></span>
</div>
<div class="image">
<img src="intem-6.jpg" alt="" />
</div>
<div class="description">
<span>DLT-19 Heavy Blaster Rifle</span>
<span>Brown</span>
</div>
<div class="quantity">
<button class="plus-btn" type="button" name="button">
<img src="plus-btn.png" alt="" />
</button>
<input type="text" name="name" value="1">
<button class="minus-btn" type="button" name="button">
<img src="minus-btn.png" alt="" />
</button>
</div>
<div id="multiple5" class="total-price">$5800</div>
</div>
<!-- Product #7 -->
<div class="item">
<div class="buttons">
<span class="delete-btn"></span>
<span class="like-btn"></span>
</div>
<div class="image">
<img src="item-7.jpg" alt="" >
</div>
<div class="description">
<span>DL-44 Heavy Blaster Pistol</span>
<span>Brown</span>
</div>
<div class="quantity">
<button class="plus-btn" type="button" name="button">
<img src="plus-btn.png" alt="" />
</button>
<input type="text" name="name" value="1">
<button class="minus-btn" type="button" name="button">
<img src="minus-btn.png" alt="" />
</button>
</div>
<div id="multiple10" class="total-price">$1500</div>
</div>
</div>
And here is my jQuery that adds up 1 on.click of my buttons.
$('.minus-btn').on('click', function(e) {
e.preventDefault();
var $this = $(this);
var $input = $this.closest('div').find('input');
var value = parseInt($input.val());
if (value >= 1) {
value = value - 1;
} else {
value = 0;
}
$input.val(value);
});
$('.plus-btn').on('click', function(e) {
e.preventDefault();
var $this = $(this);
var $input = $this.closest('div').find('input');
var value = parseInt($input.val());
if (value < 100) {
value = value + 1;
} else {
value =100;
}
$input.val(value);
});
I tried doing separately along with my searches but couldn't implement this on my other code. Just want the result to add up and decrease the price along with the on.click event of my buttons.
<html>
<head>
<title>Hello</title>
<style>
*{
font-size: 25px;
}
</style>
</head>
<body>
<button id="plus"> + </button>
<input id="quantity" type="number" value='1'>
<button id="minus"> - </button>
<div id="total">5</div>
<script>
let plus = document.getElementById('plus');
let quantityEle = document.getElementById('quantity');
let minus = document.getElementById('minus');
let total = document.getElementById('total');
let quantity = quantityEle.value;
let price = 5;
plus.addEventListener('click', function(){
quantity++;
quantityEle.value = quantity;
total.innerHTML = price * quantity;
});
minus.addEventListener('click', function(){
if(quantity > 1)
quantity--;
quantityEle.value = quantity;
total.innerHTML = price * quantity;
});
quantityEle.addEventListener('change', function(){
quantity = quantityEle.value;
total.innerHTML = price * quantity;
});
var total = $this.closest('div').find('div');
</script>
</body>
</html>
Here you go!
$('.minus-btn').on('click', function(e) {
e.preventDefault();
var $parent = $(this).closest('.item');
var $input = $parent.find('input');
var $total = $parent.find('.total-price span');
var value = parseInt($input.val());
if (value >= 1) {
value = value - 1;
} else {
value = 0;
}
$input.val(value);
$total.html(value);
calcTotal();
});
$('.plus-btn').on('click', function(e) {
e.preventDefault();
var $parent = $(this).closest('.item');
var $input = $parent.find('input');
var $total = $parent.find('.total-price span');
var value = parseInt($input.val());
if (value < 100) {
value = value + 1;
} else {
value = 100;
}
$input.val(value);
$total.html(value);
calcTotal();
});
function calcTotal() {
let total = 0;
$(".total-price span").each(function() {
total += parseInt($(this).html());
});
$('#total').html('$' + total);
}
#total {
color: red;
}
<script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script>
<!-- Product #6 -->
<div class="item">
<div class="buttons">
<span class="delete-btn"></span>
<span class="like-btn"></span>
</div>
<div class="image">
<img src="intem-6.jpg" alt="" />
</div>
<div class="description">
<span>DLT-19 Heavy Blaster Rifle</span>
<span>Brown</span>
</div>
<div class="quantity">
<button class="plus-btn" type="button" name="button">
<img src="plus-btn.png" alt="" /> +
</button>
<input type="text" name="name" value="1">
<button class="minus-btn" type="button" name="button">
<img src="minus-btn.png" alt="" /> -
</button>
</div>
<div id="multiple5" class="total-price">$<span>1</span></div>
</div>
<!-- Product #7 -->
<div class="item">
<div class="buttons">
<span class="delete-btn"></span>
<span class="like-btn"></span>
</div>
<div class="image">
<img src="item-7.jpg" alt="">
</div>
<div class="description">
<span>DL-44 Heavy Blaster Pistol</span>
<span>Brown</span>
</div>
<div class="quantity">
<button class="plus-btn" type="button" name="button">
<img src="plus-btn.png" alt="" /> +
</button>
<input type="text" name="name" value="1">
<button class="minus-btn" type="button" name="button">
<img src="minus-btn.png" alt="" /> -
</button>
</div>
<div id="multiple10" class="total-price">$<span>1</span></div>
</div>
<div>
Total: <span id="total">$2</span>
</div>
I think your question is really badly asked.
From what I understand, you seek to write an equivalence of jQuery in JS 'vanila' to increment decrement of (2, 5, 10) quantities and realize the corresponding totals.
so here is "my solution":
document
.querySelectorAll('button.minus')
.forEach(bt=>
{
bt.onclick=e=>
{
let P_parent = e.target.parentNode
, Inc = parseInt(P_parent.dataset.increment)
, U_price = parseFloat(P_parent.dataset.price).toFixed(2)
, val = parseInt(P_parent.querySelector('.quantity').value)
if (val > 0)
{
val -= Inc
P_parent.querySelector('.quantity').value = val
P_parent.querySelector('.total').textContent = '$ '+ (val * U_price).toFixed(2)
}
}
})
document
.querySelectorAll('button.plus')
.forEach(bt=>
{
bt.onclick=e=>
{
let P_parent = e.target.parentNode
, Inc = parseInt(P_parent.dataset.increment)
, U_price = parseFloat(P_parent.dataset.price).toFixed(2)
, Max = parseInt(P_parent.dataset.max)
, val = parseInt(P_parent.querySelector('.quantity').value)
if (val < Max)
{
val += Inc
P_parent.querySelector('.quantity').value = val
P_parent.querySelector('.total').textContent = '$ '+ (val * U_price).toFixed(2)
}
}
})
body { font: 14px sans-serif; padding: 1em; }
h3 { margin: 1.5em 0 0 0; }
input.quantity { width:4em; text-align: right }
.total { display: inline-block; width: 6em; text-align: right; font-weight: bold; border-bottom: 1px solid grey; margin-left: .5em }
p > button { font-weight: bold; }
<h3>by 2</h3>
<p data-increment="2" data-max=50 data-price="11">
<input class="quantity" type="text" value='0' readonly>
<button class="minus">-</button>
<button class="plus">+</button>
unit price : $11
<span class="total">$ 0</span>
</p>
<h3>by 5</h3>
<p data-increment="5" data-max=80 data-price="5.23">
<input class="quantity" type="text" value='0' readonly>
<button class="minus">-</button>
<button class="plus">+</button>
unit price : $5.23
<span class="total">$ 0</span>
</p>
<h3>by 10</h3>
<p data-increment="10" data-max=100 data-price="3.12">
<input class="quantity" type="text" value='0' readonly>
<button class="minus">-</button>
<button class="plus">+</button>
unit price : $3.12
<span class="total">$ 0</span>
</p>

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.

Categories