Trying to calculate discount from two spans - javascript

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>

Related

Selecting multiple elements with querySelectorAll and applying event in JavaScript

there is an onchange event on the input and want it to change the value of the spans with the class of "number" whenever it changes so there here is the HTML :
function myFunction() {
var x = document.getElementById("myText").value
document.querySelectorAll(".number").innerText = x
}
<div class="uper-container">
<p>Metric/Imperial unit conversion</p>
<!-- *********************************************************************************************** -->
<!-- this input will change the value of 6's span below with the class of "number" -->
<!-- ********************************************************************************************** -->
<input type="text" id="myText" placeholder="number here" value="20" onchange="myFunction()">
</div>
<div class="lower-container">
<p>Length(Meter/Feet)</p>
<p>
<span class="number"></span> meters = <span class="d"></span>feet |
<span class="number"></span> feet = <span class="d"></span>meters
</p>
<p>Volume(Liters/Gallons)
<</p>
<p>
<span class="number"></span> liter = <span class="d"></span>gallon |
<span class="number"></span> gallon = <span class="d"></span>liter
</p>
<p>Mass(Kilograms/Pounds)</p>
<p>
<span class="number"></span> kilogram = <span class="d"></span>pound |
<span class="number"></span> pound = <span class="d"></span>kilogram
</p>
</div>
so how to make spans with the class="number" have the same value as input id="myText"?
and one thing to mention is that I use scrimba editor.
Unlike jQuery, Vanilla JS will not execute innerText to every node returned by querySelectorAll with an inline call. You would need to loop through them.
The code below should work:
function myFunction() {
var x = document.getElementById("myText").value;
var spans = document.querySelectorAll(".number");
for (let i = 0; i < spans.length; i++) {
spans[i].innerText = x;
}
}
You can also use the for-of loop.
function myFunction() {
const x = document.getElementById("myText").value;
const numberElements = document.querySelectorAll(".number");
for (let element of numberElements) {
element.innerText = x;
}
}

Make multiple additions with multiple input value Javascript

I am creating a lot of numbers inside of a div. Each time someone clicks a number I want to add it to another div. Let me make myself clear with some examples:
When a user clicks on the add class, the value of .addcop should be added to the value of .totalyHide. That means the value should change to 12.
When I click on the .add2 the value should be added on to 12, so the value of .totalyhide becomes 32.80.
and other terms, if I click the first + and click the second +, they should be added together on Yearly Price.
I hope you understand what I am trying to do.
$('.add').click(function() {
$('.addcop').click();
var dp = $(".addcop").val();
var total = $(".totalyHide").val();
var bigTotal = parseFloat(total) + parseFloat(dp);
$(".totaly").val("$" + bigTotal);
});
$('.add2').click(function() {
$('.procurement').click();
var procurement = $(".procurement").val();
var total = $(".totalyHide").val();
var bigTotal = parseFloat(total) + parseFloat(procurement);
$(".totaly").val("$" + bigTotal);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.2/css/all.css" integrity="sha384-fnmOCqbTlWIlj8LyTjo7mOUStjsKC4pOpQbqyi7RrhN7udi9RwhKkMHpvLbHG9Sr" crossorigin="anonymous">
<div class="box box6">
<div class="titlet">work on it
<hr>
</div>
<div class="explain">to help you better</div>
<div class="money">
<p class="me">$12 Yearly</p><i class="add fas fa-plus-square fa-2x"></i></div>
<input type="text" name="content" class="addcop" style="display: none;" value="12">
</div>
<div class="box box5">
<div class="titlet">Procurement
<hr>
</div>
<div class="explain"></div>
<div class="money">
<p class="me">$20.80 Yearly</p><i class="add2 fas fa-plus-square fa-2x"></i></div>
<input type="text" class="procurement" style="display: none;" value="20.80">
</div>
<div class="box box8">
<div class="total">Your First Deposit will be: <input class="total1" type="button" value="$546"></div>
<input type="text" class="totalHide" style="display: none;" value="546">
<div class="total">Yearly Price: <input onchange="myFunction()" class="totaly" type="button" value="$0"></div>
<input type="text" class="totalyHide" style="display: none;" value="0">
<div class="total">On-off Price: <input class="total" type="button" value="$546"></div>
<input type="text" class="total" style="display: none;" value="546">
</div>
There is a minor issue with the JQuery code that you have written. You can add the following changes to get the desired result.
$('.add').click(function() {
$('.addcop').click();
var dp = $(".addcop").val();
var total = $(".totalyHide").val();
var bigTotal = parseFloat(total) + parseFloat(dp);
$(".totalyHide").val(bigTotal); // Add this line here
$(".totaly").val("$" + bigTotal);
});
$('.add2').click(function() {
$('.procurement').click();
var procurement = $(".procurement").val();
var total = $(".totalyHide").val();
var bigTotal = parseFloat(total) + parseFloat(procurement);
$(".totalyHide").val(bigTotal); // Add this line here
$(".totaly").val("$" + bigTotal);
});
The thing to note here is that whenever you are calculating the total,
you'll have to set that total to $(".totalyHide"), so that you can read the updated value upon next click.

Create an array that saves the quantities of an id and changes when you on click the button option

I have this code, it allows me to pick the quantities for the days and when I click on add to cart and go back to the meal, I can still see my quantities, but as you can see I have different meal options, is there a way to make the quantities consistent with the ids? that if my quantity for beef is 2 2 1, and then I go back to click chicken, it will start with the quantities I have for that meal option ?
<span>
<span class= "prices">
$15.00 - $17.00 </span>
<div class="price-options">
<span id = "price_option-1101" class="none prices">$15.00</span>
</div>
<div class="price-options">
<span id = "price_option-1102" class="none prices">$16.00</span>
</div>
<div class="price-options">
<span id = "price_option-1103" class="none prices">$17.00</span>
</div>
<br>
</span>
<button price=15 label_option= 1101 class="view1 white cbtn1 open_sansbold option protein-option">Tofu <span id="price-difference-for-1101"></span></button><button price=16 label_option= 1102 class="view1 white cbtn1 open_sansbold option protein-option">Chicken <span id="price-difference-for-1102"></span></button><button price=17 label_option= 1103 class="view1 white cbtn1 open_sansbold option protein-option">Beef <span id="price-difference-for-1103"></span></button> </center>
<br>
<div class="textCenter" style="font-weight:700">
Add this meal to the delivery days below:
<br><br>
</div>
<table>
<div class="satin background_option">
<p style="display:inline-block;margin-right:150px">Monday, May 15th</p>
<span style="float:right;">
<i id="qty-minus1" class="fa fa-minus-circle controls" style="color: #d7d6d0"></i>
<input id="qty1" type="number" value="2" min="0" step="1" style="border:1px solid #d7d6d0;background:transparent;width:35px;height:33px;color:#000;font-size:21px;font-weight:700;">
<i id="qty-plus1" class="fa fa-plus-circle controls" style="color: #d7d6d0"></i>
</span>
</div>
<div class="satin background_option" style="margin-top:10px;height:50px;">
<p style="display:inline-block;margin-right:150px">Wednesday, May 17th</p>
<span style="float:right;">
<i id="qty-minus3" class="fa fa-minus-circle controls" style="color: #d7d6d0"></i>
<input id="qty3" type="number" value="2" min="0" step="1" style="border:1px solid #d7d6d0;background:transparent;width:35px;height:33px;color:#000;font-size:21px;font-weight:700;">
<i id="qty-plus3" class="fa fa-plus-circle controls" style="color: #d7d6d0"></i>
</span>
</div>
<div class="satin background_option" style="margin-top:10px;height:50px;">
<p style="display:inline-block;margin-right:150px">Friday, May 19th</p>
<span style="float:right;">
<i id="qty-minus5" class="fa fa-minus-circle controls" style="color: #d7d6d0"></i>
<input id="qty5" type="number" value="3" min="0" step="1" style="border:1px solid #d7d6d0;background:transparent;width:35px;height:33px;color:#000;font-size:21px;font-weight:700;">
<i id="qty-plus5" class="fa fa-plus-circle controls" style="color: #d7d6d0"></i>
</span>
</div>
</table>
<center>
<a style="color:white;text-decoration:none;" href="../deliveries"><button class=" view-add white cbtn1 open_sansbold option">Back </button></a>
<button id= "add-to-cart" class=" view-disable white cbtn1 open_sansbold option" disabled> ADD TO CART </button>
</center>
</article>
I already have this JavaScript to do the pricing on the buttons
$(".protein-option").click(function() {
var this_id = $(this).attr("label_option");
var this_price = parseInt($(this).attr("price"), 10);
console.log("this_id" + this_id + "-- " + this_price);
$("#totalprice").val($(this).attr("price"));
$(".protein-option").each(function() {
var loop_id = $(this).attr("label_option");
var loop_price = parseInt($(this).attr("price"), 10);
var difference = loop_price - this_price;
var sign = Math.sign(difference);
difference = Math.abs(difference);
difference = parseFloat(difference).toFixed(2);
if(sign == 0) {
difference = "$0.00";
} else if (sign == 1) {
difference = "+$" + difference;
} else if (sign == -1) {
difference = "-$" + difference;
}
console.log(loop_id + " -- " + loop_price + " -- " + difference + " -- " + sign);
$("#price-difference-for-"+loop_id).html(difference);
});
$("#price-difference-for-"+this_id).html(" ");
});
I put this code after the onclick (I declared my array on the top of the page)
var meal_label_qty = $(this).attr("label_option");
var id_mon_qty = $("#qty1").val();
var id_tues_qty = $("#qty2").val();
var id_wed_qty = $("#qty3").val();
var id_thur_qty = $("#qty4").val();
var id_fri_qty = $("#qty5").val();
//gets meal id and qty
label_options.push(meal_label_qty);
qty_options.push(id_mon_qty,id_tues_qty,id_wed_qty,id_thur_qty,id_fri_qty);
meal_qty.push(label_options,qty_options);
alert(meal_qty);
I get the alerts correct, but how can I make them change depending on the label_option id?
here is how my code looks like
So you may want to store it in an object ( much better then searching an array ) and then restore on every change?
var quantperproduct={};
var meal_label_qty="1011";
$(".protein-option").on("click",function(){
var elements=[1,2,3,4,5].map(el=>$("#qty"+el));
var quantities=elements.map(el=>el.val());
//store them:
quantperproduct[meal_label_qty]=quantities;
//restore the new label ( if possible)
meal_label_qty = $(this).attr("label_option");
elements.forEach((el,i)=>el.val((quantperproduct[meal_label_qty]||[])[i]||0));
});

Session Storage not working

I am getting session values and trying to store it in html using Id. When I alert the value in javascript function, it shows the value in session but it does not set it in HTML.
function result() {
var quantScore = sessionStorage.getItem('quantData');
var quantAns = sessionStorage.getItem('mathQuestion');
var readingCorrectAns = sessionStorage.getItem('readcorrect');
var readingAns = sessionStorage.getItem('readans');
var audvidScore = sessionStorage.getItem('audiovideoData');
var audvidAns = sessionStorage.getItem('audiovideoQuestion');
document.getElementById("quantque").innerHTML = quantAns;
document.getElementById("quantscore").innerHTML = quantScore;
document.getElementById("readque").innerHTML = readingAns;
document.getElementById("readans").innerHTML = readingCorrectAns;
document.getElementById("audvidque").innerHTML = audvidAns;
document.getElementById("audvidscore").innerHTML = audvidScore
}
<body onload="result()">
<div class="outer">
<div class="top">Score Card</div>
<section class="section1">
<div class="border">
<details>
<summary>Quantitative Section</summary>
<p><b>Number of Questions Answered: <span id = "quantque"> </span><br>
Number of Correct Answered: <span id = "quantans"> </span><br>
Score: <span id = "qunatscore"> </span><br></b></p>
</details>
<details>
<summary>Reading Section</summary>
<p><b>Number of Questions Answered: <span id = "readque"> </span><br>
Number of Correct Answered: <span id = "readans"> </span><br>
Score: <span id = "readscore"> </span><br></b></p>
</details>
<details>
<summary>Audio/Video Section</summary>
<p><b>Number of Questions Answered: <span id = "audvidque"> </span><br>
Number of Correct Answered: <span id = "audvidans"> </span><br>
Score: <span id = "audvidscore"> </span></b></p>
</details> <br>
</div>
<h2 style="text-align : center;"> Thank You !</h2>
<input type="submit" name="submit" value="Finish" />
</div>
</div>
</body>

Change count JavaScript function

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>

Categories