update total with multiple list items by clicking on images - javascript

So I'm not entirely sure what I'm missing, but I can't seem to get the total price to add properly. I can get each individual price, though.
Basically the idea is to click on a grayed out image, it generates a list(working) and it's suppose to give a price(which is does) and if you click on another image it should update the price, which would add to the previous price.
Can someone please tell me what I'm missing or doing wrong?
Here is my fiddle: http://jsfiddle.net/lolsen7/Acnx4/2/
HTML:
<div id="station-builder">
<a class="tools4" href="#"> <img id="keyboard" class="part" src="http://placehold.it/100x100" alt="Keyboard"/><span class="info">apple keyboard</span></a>
<a class="tools5" href="#"><img id="mouse2" class="part" src="http://placehold.it/100x100" alt="Mouse" ><span class="info">apple mouse</span></a
</div>
<div id="summaryTotal">
<p>Get this system for as little as:</p>
</div>
<ul id="list">
<li>2201L elo Touchscreen monitor</li>
<li>Mac mini</li>
</ul>
Javascript:
$ //JS FOR HARDWARE SECTION
$(document).ready(function () {
$(".part").mouseover(function () {
if (this.className !== 'part selected') {
$(this).attr('src', 'http://placehold.it/100x100' + this.id + 'http://placehold.it/100x100');
}
$(this).mouseout(function () {
if (this.className !== 'part selected') {
$(this).attr('src', 'http://placehold.it/100x100' + this.id + 'http://placehold.it/100x100');
}
});
});
var list = document.getElementById("list");
var summaryTotal = document.getElementById("summaryTotal");
var sum = 0;
var total = 0;
var finalTotal = 0;
$(".part").click(function () {
if (this.className == 'part') {
$(this).attr('src', 'http://placehold.it/100x100' + this.id + 'http://placehold.it/100x100');
console.log(this);
if (this.id == 'keyboard') {
var li = document.createElement("li");
//li.setAttribute("alt","keyboard_li");
li.setAttribute("id", "keyboard_li");
li.appendChild(document.createTextNode('Keyboard'));
list.appendChild(li);
var keyboardPrice = "59";
sum = keyboardPrice * 1.2;
console.log(sum);
total = sum / 40;
console.log(total);
var span = document.createElement('span');
span.setAttribute('id', 'keyboardTotal');
summaryTotal.appendChild(span);
$('#keyboardTotal').append(total);
}
if (this.id == 'mouse2') {
li = document.createElement("li");
li.setAttribute("id", "mouse_li");
li.appendChild(document.createTextNode('Mouse'));
list.appendChild(li);
var mousePrice = "59";
sum = mousePrice * 1.2;
console.log(sum);
total = sum / 40;
console.log(total);
var span = document.createElement('span');
span.setAttribute('id', 'mouseTotal');
summaryTotal.appendChild(span);
$('#mouseTotal').append(total);
}
} else {
$(this).attr('src', 'http://placehold.it/100x100' + this.id + 'http://placehold.it/100x100');
console.log(this);
if (this.id == "keyboard") {
$("#keyboard_li").remove();
$('#keyboardTotal').remove();
}
if (this.id == "mouse2") {
$("#mouse_li").remove();
}
}
$(this).toggleClass('selected');
});
total = $('#keyboardTotal') + $('#mouseTotal');
});

Can you make the following changes?
var kbtotal = 0;//added
var mstotal = 0;//added
var keyboardPrice = 59;
sum = keyboardPrice * 1.2;
console.log(sum);
kbtotal = sum / 40; // changed
console.log(kbtotal); // changed
var mousePrice = 59;
sum = mousePrice * 1.2;
console.log(sum);
mstotal = sum / 40; // changed
console.log(mstotal); // changed
var finaltotal = parseFloat(kbtotal) + parseFloat(mstotal);
$('#finaltotal').text(finaltotal); // added
<div id="summaryTotal">
<p>Get this system for as little as: <div id="finaltotal"></div></p>
</div>

Related

html not appending to the carousel on popover

I Am Trying to make a popover with a bootstrap carousel and where the carousel items are to be generated and appended from a script but I get the carousel but I am unable to append the item. I tried hard but I didn't come up with a solution.
the HTML initialized is as below
HTML:
<div class="popup" data-popup="popup-1">
<div class="popup-inner">
<i class="fas fa-bars"></i>
<div class="frame">
<div id='carousel' class='carousel slide' data-bs-ride='carousel'>
<div class='carousel-inner items-slider1'>
</div>
</div>
</div>
</div>
</div>
the script I have tried was
Javascript:
function findallchord(currentchord , currenttype) {
for (let i = 1; i < 10; i++) {
if (Raphael.chord.find(currentchord ,currenttype,i)) {
Raphael.chord("div3", Raphael.chord.find(currentchord , currenttype,i), currentchord +' ' +currenttype).element.setSize(75, 75);
}
}
}
var getChordRoots = function (input) {
if (input.length > 1 && (input.charAt(1) == "b" || input.charAt(1) == "#"))
return input.substr(0, 2);
else
return input.substr(0, 1);
};
$('.popup').on('shown.bs.popover', function () {
$('.carousel-inner').carousel();
});
$('[data-bs-toggle="popover"]').popover({
html: true,
content: function() {
return $('.popup').html();
}}).click(function() {
var oldChord = jQuery(this).text();
var currentchord = getChordRoots(oldChord);
var currenttype = oldChord.substr(currentchord.length);
findallchord(currentchord , currenttype);
var chordsiblings = $('#div3').children().siblings("svg");
for (let i = 1; i < 10; i++) {
if (Raphael.chord.find(currentchord , currenttype,i)) {
var itemid = "chord" + i;
var theDiv = "<div class='carousel-item"+((itemid=="chord1") ? ' active':'')+" ' id='"+currentchord+''+itemid+"'> "+chordsiblings[i-1].outerHTML+" </div>";
$('.items-slider1').append(theDiv);
}
}
});
I have also tried appendTo also as
$(theDiv).appendTo('.items-slider1');
Please Help to solve this
This is the output I get, the appended elements are not in the carousel
Note: I am using Bootstrap 5
Try instantiating the carousel after you've set it up
/*
$('.popup').on('shown.bs.popover', function () {
$('.carousel-inner').carousel();
});
*/
$('[data-bs-toggle="popover"]').popover({
html: true,
content: function() {
return $('.popup').html();
}}).click(function() {
var oldChord = jQuery(this).text();
var currentchord = getChordRoots(oldChord);
var currenttype = oldChord.substr(currentchord.length);
findallchord(currentchord , currenttype);
var chordsiblings = $('#div3').children().siblings("svg");
for (let i = 1; i < 10; i++) {
if (Raphael.chord.find(currentchord , currenttype,i)) {
var itemid = "chord" + i;
var theDiv = "<div class='carousel-item"+((itemid=="chord1") ? ' active':'')+" ' id='"+currentchord+''+itemid+"'> "+chordsiblings[i-1].outerHTML+" </div>";
$('.items-slider1').append(theDiv);
}
}
$('.carousel-inner').carousel();
});
It was needed to do call the click function first before popover as below
$('[data-bs-toggle="popover"]').click(function() {
var oldChord = jQuery(this).text();
var currentchord = getChordRoots(oldChord);
var currenttype = oldChord.substr(currentchord.length);
findallchord(currentchord , currenttype);
var chordsiblings = $('#div3').children().siblings("svg");
for (let i = 1; i < 10; i++) {
if (Raphael.chord.find(currentchord , currenttype,i)) {
var itemid = "chord" + i;
var theDiv = "<div class='carousel-item"+((itemid=="chord1") ? ' active':'')+" ' id='"+currentchord+''+itemid+"'> "+chordsiblings[i-1].outerHTML+" </div>";
$('.items-slider1').append(theDiv);
}
}
}).popover({
html: true,
content: function() {
return $('.popup').html();
}});

How to decrement each click of the animation

I am trying to create animation game. Animation game must consits of One image alternating with another every half a second. I am intended to count++ on each click of the happy-face fish and count-- on each sad-face fish clicked. But, my code is only incrementing, whatever the image is clicked. Also,my code shows me two different images while It must have to be only one.
I have to count a click while my animation is running ( animation: images should be alternating every half a second. It will look like fish is smiling for half second and then crying for another half second then repeats). If i click on happy face, I will score 1 and if click on sad-face I will lose 1. In the end it must show you win if i achieve 10 and resets again on clicking Start Animation.
[Output should be like this:][1]
var image = "happy";
var totalscore = 0;
var counter = 0;
var Schedule;
function happyFish() {
totalscore++;
var happyclickSpan = document.getElementById("score");
happyclickSpan.innerHTML = totalscore;
counter = counter + 1;
if (counter == 10) {
clearInterval(Schedule);
var finalwords = document.getElementById("d");
finalwords.innerHTML = "Your Score:" + counter + " Game Over. You Win!";
}
}
function sadFish() {
totalscore--;
var sadclickSpan = document.getElementById("score");
sadclickSpan.innerHTML = totalscore;
counter = counter - 1;
if (counter == -10) {
clearInterval(Schedule);
var finalwords = document.getElementById("d");
finalwords.innerHTML = "Your Score:" + counter + " Game Over. You Lose!";
}
}
function StartAnimation() {
counter = 0;
totalscore = 0;
fish_img = document.getElementById("happy_fish");
f_img = document.getElementById("happy_fish");
fish_img.classList.add('on');
Schedule = setInterval(animationfunction, 500);
}
function animationfunction() {
if (image == "happy") {
image = "sad";
fish_img.src = "https://www.uow.edu.au/~dong/w3/assignment/a5/sad_fish.png";
} else {
image = "happy";
fish_img.src =
"https://www.uow.edu.au/~dong/w3/assignment/a5/happy_fish.png";
}
}
<img src="https://www.uow.edu.au/~dong/w3/assignment/a5/happy_fish.png" alt="" id="happy_fish" onClick="happyFish()">
<img src="https://www.uow.edu.au/~dong/w3/assignment/a5/sad_fish.png" alt="" id="sad_fish" onClick="sadFish()">
<br>
<h1 id="d">
Your Score: <span id="score">0</span>
</h1>
I modified your StartAnimation and animationfunction methods to make the fish dissapear with a toggle instead of trying to modify the source of the image.
I made it with a css class off which will make a fish dissapear with display: none;
var totalscore = 0;
var counter = 0;
var Schedule;
function happyFish() {
totalscore++;
var happyclickSpan = document.getElementById("score");
happyclickSpan.innerHTML = totalscore;
counter = counter + 1;
if (counter == 10) {
clearInterval(Schedule);
var finalwords = document.getElementById("d");
finalwords.innerHTML = "Your Score:" + counter + " Game Over. You Win!";
}
}
function sadFish() {
totalscore--;
var sadclickSpan = document.getElementById("score");
sadclickSpan.innerHTML = totalscore;
counter = counter - 1;
if (counter == -10) {
clearInterval(Schedule);
var finalwords = document.getElementById("d");
finalwords.innerHTML = "Your Score:" + counter + " Game Over. You Lose!";
}
}
function StartAnimation() {
counter = 0;
totalscore = 0;
var initialWords = document.getElementById("d");
initialWords.innerHTML = "Your Score: <span id=\"score\">0</span>";
Schedule = setInterval(animationfunction, 500);
}
function animationfunction() {
var fish_img = document.getElementById("happy_fish");
var f_img = document.getElementById("sad_fish");
fish_img.classList.toggle('off');
f_img.classList.toggle('off');
}
.off {
display: none;
}
<button onClick="StartAnimation()">Start Animation</button>
<br>
<img src="https://www.uow.edu.au/~dong/w3/assignment/a5/happy_fish.png" alt="happy" id="happy_fish" onClick="happyFish()">
<img src="https://www.uow.edu.au/~dong/w3/assignment/a5/sad_fish.png" alt="sad" id="sad_fish" class="off" onClick="sadFish()">
<br>
<h1 id="d">
Your Score: <span id="score">0</span>
</h1>
You can make things a lot simpler by having one img element and one click handler.
In the snippet I merged the two click handlers into one and added a check for the state of the fish (being represented now by the boolean isHappy).
I attached this handler to a single img element in your HTML and in the animation function I alternate its src attribute between the happy and sad fish according to the isHappy state.
Additionally, Since the counter and the total score are the same, I use only the total score variable.
var isHappy = true;
var totalscore;
var Schedule;
function clickFish() {
if (isHappy) {
totalscore++;
} else {
totalscore--;
}
var scoreSpan = document.getElementById("score");
scoreSpan.innerHTML = totalscore;
if (totalscore === 10) {
clearInterval(Schedule);
var finalwords = document.getElementById("d");
finalwords.innerHTML = "Your Score:" + totalscore + " Game Over. You Win!";
}
}
function StartAnimation() {
isHappy = true
totalscore = 0;
clearInterval(Schedule);
Schedule = setInterval(animationfunction, 500);
}
function animationfunction() {
fish_img = document.getElementById("fish");
isHappy = !isHappy;
if (isHappy) {
fish_img.src = "https://www.uow.edu.au/~dong/w3/assignment/a5/happy_fish.png";
} else {
fish_img.src = "https://www.uow.edu.au/~dong/w3/assignment/a5/sad_fish.png";
}
}
<button onclick="StartAnimation()">Start animation</button><br />
<img src="https://www.uow.edu.au/~dong/w3/assignment/a5/happy_fish.png" alt="" id="fish" onClick="clickFish()">
<br>
<h1 id="d">
Your Score:
<span id="score">0</span>
</h1>

how to link pagination to pagescroll in jquery?

I have created a carousel in javascript to show multiple contents either by using page scroll or by clicking a button. I have used viewpager.js for this purpose. I have added a pagination at the bottom which works fine when the buttons are clicked. I am unable to figure out how to link it to the page scroll. Any help is appreciated. My code:
HTML
<div id='prev'>
<button id="btn-prev"><img src='img/orange-towards-left.png'></button>
</div>
<div class='pager'>
<div class='pager_items' id='info'>
</div>
</div>
<div id='next'>
<button id="btn-next"><img src='img/orange-towards-right.png'></button>
</div>
<div id='pagination'>
<ul></ul>
</div>
JS
item_container = document.querySelector('.pager_items');
view_pager_elem = document.querySelector('.pager');
w = view_pager_elem.getBoundingClientRect().width;
items = payerAccArr.length;
item_container.style.width = (items * 100)+ '%';
var child_width = (100 / items) + '%';
var html = "";
document.getElementById('monthInfo').innerHTML=payerAccArr[0].DateKey + " Bill Amount ";
for (var i = 0; i < items; i++) {
html += "<div class=toggle><h4>Payer Account Name</h4> <ul> <li>" + payerAccArr[i].PayerAccountName +
"</li></ul> _______________ <ul><li> "+(payerAccArr[i].TotalAmount).toFixed(2) +
" USD</li> </ul></div>";
}
item_container.innerHTML = html;
for(var i=0;i<items;i++)
item_container.children[i].style.width = child_width;
var htmlStr='<li class="current"></li>';
for(var i=0;i<items-1;i++){
htmlStr += '<li></li>';
}
$('#pagination ul').html(htmlStr);
vp = new ViewPager(view_pager_elem, {
pages: item_container.children.length,
vertical: false,
onPageScroll : function (scrollInfo) {
offset = -scrollInfo.totalOffset;
invalidateScroll();
},
onPageChange : function (page) {
document.getElementById('monthInfo').innerHTML=payerAccArr[page].DateKey + " Bill Amount ";
}
});
window.addEventListener('resize', function () {
w = view_pager_elem.getBoundingClientRect().width;
invalidateScroll();
});
document.getElementById('btn-prev').addEventListener('click', function (){
vp.previous();
if(index>0){
createDoughnutChart(index--);
}
var li = jQuery("li.current");
if (li.length){
var $prev = li.prev();
if($prev.length == 0)
$prev = $("#pagination li").last().addClass("current");
li.removeClass("current");
$prev.addClass("current");
}
});
Similar code for the next button also has been written.
This issue got solved. I made a change to the onPageChange function by adding the following code. I am now able to link it to both the page scroll and the buttons.
JS:
onPageChange : function (page) {
document.getElementById('monthInfo').innerHTML=payerAccArr[page].DateKey + " Bill Amount ";
// console.log('page', page);
var li = $("li.current");
var curIndex = li.index();
if(li.length){
var $prev = li.prev();
var $next = li.next();
if(page == $prev.index()){
li.removeClass("current");
$prev.addClass("current");
}
if(page==$next.index()){
li.removeClass("current");
$next.addClass("current");
}
}
}

Adding variables and output to html

I am using Bootstrap buttons set with data-toggle="button" that toggles the active class on the button so I figured I would use hasClass to update the variables. As you can tell I am new to javascript/jquery. I then push the variables out to html and want it to update based on the buttons being selected or de-selected, I just can't quite what method I should use. Is AJAX necessary?
Snippet:
var priceA = 300;
var priceB = 400;
var imgBtn = 0;
var mscBtn = 0;
var outputPrice = priceA + imgBtn + mscBtn;
$('#showPrice').html(outputPrice);
$('.priceTable button').click(function() {
$(this).toggleClass('active');
if ($(this).hasClass('active')) {
imgBtn = 25;
} else {
imgBtn = 0;
}
$('#showPrice').html(outputPrice);
});
.active {background-color:red;}
<link href="https://stackpath.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h2 id="showPrice"></h2>
<table class="priceTable">
<tr>
<td>
<button type="button" class="btn btn-lg priceButton imageBtn" id="imageBtn">Image Gallery</button>
<button type="button" class="btn btn-lg priceButton" id="musicBtn" role="button" aria-pressed="false">Music Player</button>
</td>
</tr>
</table>
Use jQuery's click() and hasClass() to check and trigger your variable updates
Something like this:
$('#imageBtn').click(function(){
if ($(this).hasClass("active")){
imgBtn = 25;
}
});
Problem solved! I am sure there is a much easier way but this is what I was able to figure out and it works. Any improvement suggestions would be appreciated as I use them as a learning experience.
Here is jquery that includes additional buttons. When a button is selected, it adds that to the price range of priceA and priceB. When deselected, it reduces it again from the price range.
var priceA = 300;
var priceB = 400;
var imgBtn = 0;
var mscBtn = 0;
var vidBtn = 0;
var strBtn = 0;
var blgBtn = 0;
var othBtn = 0;
$('#showPrice, #showPrice2').html('$' + priceA + ' - ' + '$' + priceB);
$('.priceTable button').click(function(){
$(this).toggleClass('active');
if($('.imageBtn').hasClass('active')) {
imgBtn = 25;
} else {imgBtn = 0;}
if($('.musicBtn').hasClass('active')) {
mscBtn = 50;
} else {mscBtn = 0;}
if($('.videoBtn').hasClass('active')) {
vidBtn = 50;
} else {vidBtn = 0;}
if($('.storeBtn').hasClass('active')) {
strBtn = 75;
} else {strBtn = 0;}
if($('.blogBtn').hasClass('active')) {
blgBtn = 75;
} else {blgBtn = 0;}
if($('.otherBtn').hasClass('active')) {
othBtn = 75;
} else {othBtn = 0;}
});
function calcPrice (){
var outputPriceA = priceA + imgBtn + mscBtn + vidBtn + strBtn + blgBtn + othBtn;
var outputPriceB = priceB + imgBtn + mscBtn + vidBtn + strBtn + blgBtn + othBtn;
$('#showPrice, #showPrice2').html('$' + outputPriceA + ' - ' + '$' + outputPriceB);
};

how to remove added item in cart?

i am trying make drag and drop shopping cart. By the help from some site on internet i am able to add the item in the cart and also it calculates the total price. But i am unable to remove a selected item fro the cart. I am very new to javascript and html5, so please help me..
the code is:
<script>
function addEvent(element, event, delegate ) {
if (typeof (window.event) != 'undefined' && element.attachEvent)
element.attachEvent('on' + event, delegate);
else
element.addEventListener(event, delegate, false);
}
addEvent(document, 'readystatechange', function() {
if ( document.readyState !== "complete" )
return true;
var items = document.querySelectorAll("section.products ul li");
var cart = document.querySelectorAll("#cart ul")[0];
function updateCart(){
var total = 0.0;
var cart_items = document.querySelectorAll("#cart ul li")
for (var i = 0; i < cart_items.length; i++) {
var cart_item = cart_items[i];
var quantity = cart_item.getAttribute('data-quantity');
var price = cart_item.getAttribute('data-price');
var sub_total = parseFloat(quantity * parseFloat(price));
cart_item.querySelectorAll("span.sub-total")[0].innerHTML = " = " + sub_total.toFixed(2);
total += sub_total;
}
document.querySelectorAll("#cart span.total")[0].innerHTML = total.toFixed(2);
}
function addCartItem(item, id) {
var clone = item.cloneNode(true);
clone.setAttribute('data-id', id);
clone.setAttribute('data-quantity', 1);
var btn=document.createElement('BUTTON');
btn.className = 'remove-item';
var t=document.createTextNode("X");
btn.appendChild(t);
cart.appendChild(btn);
clone.removeAttribute('id');
fragment = document.createElement('span');
fragment.setAttribute('class', 'sub-total');
clone.appendChild(fragment);
cart.appendChild(clone);
$('#product').on('click','.remove-item',function(){
$(this).closest('li').remove();// remove the closest li item row
});
}
function updateCartItem(item){
var quantity = item.getAttribute('data-quantity');
quantity = parseInt(quantity) + 1
item.setAttribute('data-quantity', quantity);
var span = item.querySelectorAll('span.quantity');
span[0].innerHTML = ' x ' + quantity;
}
function onDrop(event){
if(event.preventDefault) event.preventDefault();
if (event.stopPropagation) event.stopPropagation();
else event.cancelBubble = true;
var id = event.dataTransfer.getData("Text");
var item = document.getElementById(id);
var exists = document.querySelectorAll("#cart ul li[data-id='" + id + "']");
if(exists.length > 0){
alert("Already present");
} else {
addCartItem(item, id);
}
updateCart();
return false;
}
function onDragOver(event){
if(event.preventDefault) event.preventDefault();
if (event.stopPropagation) event.stopPropagation();
else event.cancelBubble = true;
return false;
}
addEvent(cart, 'drop', onDrop);
addEvent(cart, 'dragover', onDragOver);
function onDrag(event){
event.dataTransfer.effectAllowed = "move";
event.dataTransfer.dropEffect = "move";
var target = event.target || event.srcElement;
var success = event.dataTransfer.setData('Text', target.id);
}
for (var i = 0; i < items.length; i++) {
var item = items[i];
item.setAttribute("draggable", "true");
addEvent(item, 'dragstart', onDrag);
};
});
</script>
and
<section id="product">
<ul class="clear">
<li data-id="1">
<a href="#">
<img src="a.jpg" alt="">
<h3>item 1</h3>
<p>xyz</p>
</a>
</li>
</ul>
</secton>
and css is:
<style>
ul, li{
list-style: none;
margin: 0px;
padding: 0px;
cursor: pointer;
}
section#cart ul{
height: 200px;
overflow: auto;
background-color: #cccccc;
}
</style>
Add a close button to every cart item like
<input type="button" class="remove-item" value="X" />
Try this to remove the item-row,
$('#product').on('click','.remove-item',function(){
$(this).closest('li').remove();// remove the closest li item row
});
Then Try this to remove the item in the cart
$(".remove").click(function(e) {
pid = $(this).siblings("#checkIDinput:hidden").attr("value");
Or--------------------
$(".remove").click(function(e) {
pid = $(this).siblings("input:hidden").attr("value");

Categories

Resources