Home > Back-end >  How can I use Javascript to gather prices on my page to add to total?
How can I use Javascript to gather prices on my page to add to total?

Time:05-12

I have a product page that recently had a product add-on tool made for it. I am modifying the code to change it's format a bit. There is a "add to cart" button bar that displays the total price before adding to cart.

Bottom Cart Bar

I used .innerHTML to match the price of the top of the page for consistency, but I am trying to include the price of the product addons once selected.

Current code for bottom bar:

  var selector1 = ".top-bar";
  var el1 = document.querySelector(selector1);
  var selector2 = ".bottom-bar";
  var el2 = document.querySelector(selector2);
  var totalPriceSelected = '';
  
  function getPrice() {
     
     el2.innerHTML = el1.innerHTML;
  };
  

  document.addEventListener('variant:priceChange', ()=>{
     getPrice();

  });

The add-on tool is a vue app which I am a little new to. I managed to get to the point that I can get the addons to print the prices to the console once selected:

watch: {
      selected: function(new_value) {
            
        
          setTimeout(function(){    
            var priceSelected = document.querySelectorAll(".price_selected");
            var strippedPriceSelected = priceSelected;
            for(var i=0;i<strippedPriceSelected.length;i  ){
            var totalPriceSelected = priceSelected[i].innerHTML;
            console.log(totalPriceSelected);
            }
          }, 10);
        
        this.product.selected = new_value;
        //this.$emit('selected', this.product, new_value);
        
      }
Console log

Currently, once the add-on products are selected, the vue adds the class of ".price_selected" to the price element once it is selected. The code above looks for ".price_selected", saves it to the variable totalPriceSelected, then prints it to the console.

I am wondering how I can add all of the addon price values (once selected) to the total price in the add to cart bar. I'd imagine I'd have to convert all the prices to numbers instead of strings and add them together, but I'm not quite sure how to do that.

Product page for reference

UPDATE

watch: {
      selected: function(new_value) {

          setTimeout(function(){
            var priceTotal = 0
            var priceSelected = document.querySelectorAll(".price_selected");
            var strippedPriceSelected = priceSelected;
            for(var i = 0; i < strippedPriceSelected.length; i  ){
              var totalPriceSelected = priceSelected[i].innerHTML; // ' $ 85.00'
              var priceNumber = parseFloat(totalPriceSelected.split(' ')[1]);
                priceTotal  = priceNumber;
                
            }
            var currentBottomPrice = parseFloat(el2.innerHTML);
            el2.innerHTML = currentBottomPrice  = parseFloat(priceTotal);
            console.log(priceTotal);
          }, 10);

        this.product.selected = new_value;
        //this.$emit('selected', this.product, new_value);
        
      }
      
    },

So I have this now which is adding them correctly, but when the value of priceTotal goes back to 0 (add-ons are deselected) the total stays the same because it added the value and it is tr

CodePudding user response:

Yeah so you can split the price string into two parts on the space, then parse the second part as a float (decimal number). Now you can do any math you need to it.

setTimeout(function() {    
  var priceSelected = document.querySelectorAll(".price_selected");
  var strippedPriceSelected = priceSelected;
  for(var i = 0; i < strippedPriceSelected.length; i  ){
    var totalPriceSelected = priceSelected[i].innerHTML; // ' $ 85.00'
    var priceNumber = parseFloat(totalPriceSelected.split(' ')[1]);
    console.log(priceNumber) // Prints 85 as number
  }
}, 10);

Let me know if you have any questions or it doesn't work, I'd be happy to help!

CodePudding user response:

We shouldn't just seek to have a working piece of code that solves a minor issue but could pose a major functionality break later. I see potential pitfalls around the approach used here:

a) converting from string to number (using Number/parseFloat) could pose issues if the string contains invalid characters. For e.g., if price is from the add-on is displayed as ' $85.00' (notice the missing space after $ symbol), totalPriceSelected.split(' ')[1] will return undefined. Adding undefined to a number will give you NaN. Or, what if the add-on starts displaying the price as '85.00 $'. The approach used above would fail again.

b) What if the vue component updates the CSS class for prices to something else, say amount_selected? Such a change would be beyond your control but has a direct impact on the code/logic that you would implement to display the total price. Needless to say, when it comes to dealing with showing/requesting prices from users, we should be extremely careful about it.

There could be more such cases and we should look for a solution that is more robust.

  • Related