Help finding a way to calculate tip for my shopping cart

Hi there,

I have been stuck on coding a tip button for my shopping cart I have been working on. The cartRows with associated images, quantity, and price are added upon clicking the Add To Cart button. From there subtotal, tax, delivery fee, and total can be easily calculated.

I was wondering how to code for a tip. A button would be pressed after the user enters a custom tip, but I can’t get anything to work so far. The code for generating a tip is placed within a for loop, I think I’m getting stuck there, how to account for a button within a for loop, I can’t find any resources to help and I’ve been searching for a week or so.

The link to my code is here: https://codepen.io/emilysarah1/pen/jOyGRXg

Hey e75schob!
I’d like to help you, could you just post the code snippet related to the tip feature you want to implement.
Also post a description about your logic and where do you think you’re stuck.

Cheers,

I would add a click-eventlistener similar to what you do for the purchase-button on line 28. But make the event-listener reference the “Custom tip” button and fire a function called something like addTip. Start off this function with a console.log printing a msg to the console and make sure the button works in the console before proceeding. When that is working, add logic to this function to get the tip amount from the input box, add it to the total and update the total.

It looks like the for-loop is used to add many event-listeners for the “Add to cart” and “Remove” products. That makes sense since we have many products available and the cart could consist of many products. But since you only need one tip-button, a for-loop is not necessary when adding the tip button. Also, the logic starts getting complicated enough that you may want to consider a UI-library/framework such as React although it’s definitely doable in vanilla JS.

I see you have the link: https://codepen.io/emilysarah1/pen/MWJEYaM

I’m a beginner to JavaScript, just keep this in mind the code below might be way off.

To calculate tip, I decided to write a separate addEventListener as follows:

document.getElementsByClassName(‘customTipBtn’)[0].addEventListener(‘click’, addTip),

But I don’t know where to place it? It obviously a standalone entity. But I don’t get how addTip() could be connected to calculating sales tax, fee, subtotal, etc. since they are all calculated in the updateCartTotal() function.

I decided to write a separate function for the addTip, so something like this:

To make sure it is working, I had an alert (“WoHOO”) message. So the total code snippet is as follows:

document.getElementsByClassName(‘customTipBtn’)[0].addEventListener(‘click’, addTip)

function addTip(){
//get the tip amount from the input box, do by id or by returns a collection of elements
var tipAmt = document.getElementsByClassName(“customElem”)[0].value

var subtotalAmt = document.getElementsByClassName(‘subtotal-totals-value’)[0].value

var tipprcnt = (tipAmt / 100) * (subtotalAmt);

//add it to the total
var totalAmt = subtotalAmt + tipprcnt

//update the total
document.getElementsByClassName(‘totals-value’).innerText = totalAmt.toFixed(2);

alert(“WoHOO!”)

}

don’t worry, we’re going to figure it out together.
I asked for a specific code snippet because there’s a lot of code in your codepen, and I don’t feel comfortable analysing it all, I hoped to be able to go surgical on this.

Also add three backticks ``` before and after you paste code in here in order to make it look more visible (how to format code before posting).

Try the solution suggested by @mike7127143742 and let us know how it goes

Cheers,

document.getElementsByClassName('customTipBtn')[0].addEventListener('click', addTip)
 
function addTip(){

  var tipAmt = document.getElementsByClassName("customElem")[0].value
 
 
  var subtotalAmt = document.getElementsByClassName('subtotal-totals-value')[0].value
  
   var tipprcnt = (tipAmt / 100) * (subtotalAmt);
 
  
var totalAmt = subtotalAmt + tipprcnt
  

 document.getElementsByClassName('totals-value').innerText = totalAmt.toFixed(2);
 
  alert("WoHOO!")

    } 
//THE relevant HTML

 
       <div class="cart-total-title"></div>
              <label class="align">Subtotal</label>
                <span class="subtotal-totals-value">$0</span>
      
      <div class="cart-total-title"></div>
              <label class="align">Restaurant Delivery Fee</label>
                <span class="fee-totals-value">$0</span>
 
           
<div class="cart-total-title"></div>
              <label class="align">Sales Tax</label>
                <span class="tax-totals-value">$0</span>


<div class="cart-total-title"></div>
              <label class="align">Tip</label>
    
<label>Custom:</label><input type="text" id="customTip" class="customElem"> 
      <button class="customTipBtn">Custom Tip</button>

      
      <span class="tip-totals-value">$0</span>
           
<br>
  
  <div class="cart-total-title">
                <label class="align">Grand Total</label>
     
       
 <span class="totals-value">$0</span>
      
  </div>

This is what I have for adding tip as seen above, I tried to format like you said, not sure if it works but hope it is readable. The only thing I get working is WoHOO! when I press the button, lol.

The other function I will mention is updateCartTotal(), not sure you want to see this, it can be seen in CodePen but it calculates subtotal, total, fee, and tax. Tip could be done in this function, but I just have one tip button so was told to write a separate function, and I attempted to do this.

Hope this helps,

Emily S.

Hey e75schob you also an early bird? :slight_smile:
You did good with the formatting, great! :call_me_hand:

The first thing that comes to mind seeing this code is this line:
document.getElementsByClassName('totals-value').innerText = totalAmt.toFixed(2);

Your getting back an HTML collection (kind of an array, but not quite) from the method .getElementsByClassName, it cannot have an .innerText property, because it’s a collection of several items, so you either loop through it, specify your item (as you do in other parts of your code) or you either change all together the approach and use an id html attribute instead of a class attribute to identify where in the html you want to make appear the value of your tip.

Let me know if this helps. :slight_smile:

1 Like

Looks like you are progressing. I noticed this line in the codepen now:

 document.getElementById('customTip').value = (Math.floor((Math.random() * 50) + 1) + "%");

The issue here is that you concatenate a number with a string (the % sign). Now when you try to do math operations on the resulting string, you get this NaN warning (which means Not a number). If you comment out this entire line, enter a number in the tip box, and press the button it should work and tip button will essentially update total price. To improve this and not allow text-entries in the field for tip, I would change the input-type of the tip-field in html to be of the type number or possibly range (you currently have type set to text, and add min/max/value attributes.

1 Like

Thanks! It works fine now.
I really appreciate the help!
Emily

2 Likes