Difficulties encountered when trying to load liquid using Javascript

Having trouble loading the Shopify liquid object {{product.price | json}} into JS, as it's displaying NaN with the current code on the front end. Any suggestions on how to properly pass liquid into JS?

I've tried two functions but neither seem to be working with the Shopify product price. Using a static number has been successful, but I need the price to be dynamic as expected.

<div class="afterpay-section" id="afterpay" v-for="item in items" v-bind:class="{'afterpay-label': afterpayAlert}">
   ${ afterpayPayments } 
</div>

<script> 
  const app = new Vue({
    el: '#afterpay',
    data: {
      textColor: {
        color: 'red',
      },
      textFont: {
        'font-weight': 'bold',
      },
      afterpayMessage: 'Or 4 payments of',
      withAfterpay: 'with AfterPay',
      failedAlertOne: '',
      failedAlertTwo: '',
      items: [
          { price: {{ product.price | money_without_trailing_zeros | json }} },
      ],
    },
    delimiters: ['${', '}'],

    computed: {
      afterpayAlert: function() {
        if (this.failedAlertOne) {
          return this.failedAlertOne + ' ' + this.failedAlertTwo;
        } else {
          return this.afterpayMessage + ' ' + {{ product.price | money_without_trailing_zeros | json }} + ' ' + this.withAfterpay;
      }
    },

    afterpayCal() {
      let productPrice = '{{ product.price | money_without_trailing_zeros | json }}';
      let afterpayDiscount = 4;
      let totalPrice = productPrice / afterpayDiscount;
        if(this.afterpayMessage) {
          return this.afterpayMessage + ' ' + {{ product.price | money_without_trailing_zeros | json }} + ' ' + this.withAfterpay;
        }
      },

     afterpayPayments () {
       let productPrice = '{{ product.price | money_without_trailing_zeros | json }}';
       return this.afterpayMessage  + ' ' + ((productPrice / 4) / 100 ).toFixed(2) + ' ' + this.withAfterpay;
      }
    },    
  })
</script>

<style>
  .afterpay-label {
    background-color: transparent;
    color: #000;
    padding: 10px 0;
    margin: 5px 0;
  }
</style>

Answer №1

When utilizing the money filter, it is important to note that the output will likely be in the format of a string such as "$50" or similar. Utilizing this value in calculations like

((productPrice / 4) / 100 ).toFixed(2)
will result in NaN without proper modification.

To avoid this issue, either refrain from using the money filter altogether or ensure that you remove any extra characters such as $ before performing calculations with the obtained value.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

When you download a file through the unpkg CDN, the size of the npm package is

I am experiencing a discrepancy with the file size of a file in my npm package. The file is 307kb in size, but when I download it through unpkg, the same file is only 73.2Kb. I find it quite puzzling how the file can be smaller when downloaded over the net ...

Prevent the browser back button from being used in a web application that requires CLIENT_CERT authentication

My website utilizes CLIENT_CERT JAAS authentication and is compatible with IE7. After logging out, when I return to the home page and click on the back button, I want to stay on the same non-secure page. I have been able to achieve this using the history. ...

``There seems to be an issue with the redirect header function in the PHP

Setting up my test site on a local host, I included an ajax request in one of my java-script files to a php script. if(hIF == "true"){ $.ajax({ type: "POST", url: "log_in/login.php", data: {name: userName, pwd: password}, ...

Is it common for the vuetify main.sass bundle file to have a gzipped size of 30 kilobytes?

Just a quick question: Is the file size considered normal? Will it still contain all component stylings even if removed by treeshaking? Treeshaking is enabled. Any advice would be greatly appreciated! https://i.stack.imgur.com/VKaQQ.png ...

AngularJS dynamically creates an HTML template that includes an `ng-click` attribute calling a function with an argument

Struggling to create an HTML template using an AngularJS directive, the issue arises when trying to pass an object into a function within one of the generated elements. Here is the directive code in question: app.directive('listObject', function ...

Can the default position of the scrollbar be set to remain at the bottom?

I have a select option tag with a scrollbar to view the contents in the dropdown. I am looking for a way to automatically position the scroll at the bottom when an item is selected from the dropdown. jquery code $('document').ready(func ...

Is it possible for me to convert my .ejs file to .html in order to make it compatible with Node.js and Express?

I have an index.html file and I wanted to link it to a twitter.ejs page. Unfortunately, my attempts were unsuccessful, and now I am considering changing the extension from ejs to html. However, this approach did not work either. Do .ejs files only work wit ...

Using the ref callback to access getBoundingClientRect values in React Components

I'm having some trouble extracting data using the getBoundingClientRect() method from a set of animated div elements. The issue I'm facing is that the refCallback function is returning empty DOMRect objects. If you're interested, feel free t ...

Playing out the REST endpoint in ExpressJS simulation

Suppose I have set up the following endpoints in my ExpressJS configuration file server.js: // Generic app.post('/mycontext/:_version/:_controller/:_file', (req, res) => { const {_version,_controller,_file} = req.params; const ...

Unusual div image alignment when dimensions are dynamically adjusted with Javascript animations

I have created a basic webpage using JavaScript that aims to scale an element from the center of the page over time when clicked. It is functioning properly for the SVG element I tested it with. However, when I use an image, it initially appears outside o ...

Can I trust the security of my credentials if they are able to be logged in the console

While working with NextJS, I've encountered a challenge in applying server-side rendering methods like getStaticProps to maintain credentials on the server rather than exposing them to the client. Despite my attempts, I couldn't find a straightfo ...

Using two loops/arrays in JavaScript to generate a rating score

I want to create a simple rating component with the following appearance: ◼◼◼◻◻ (score: 3 out of 5) Here is my JSX code snippet: var score = 3; var range = 5; { [...Array(range)].map((e, i) => ( <div className="rating-item" ...

Using Node.js to execute JavaScript with imported modules via the command line

Having limited experience with running JavaScript from the command line, I am facing a situation where I need to utilize an NPM package for controlling a Panasonic AC unit, which includes a wrapper for their unofficial API. My objective is to create a sim ...

Creating a unique local storage cache mechanism for AJAX requests in jQuery

Recently, I attempted to develop a personalized caching system for my ajax requests, primarily focused on data retrieval. Instead of storing the information in the browser cache, I decided to store it in localStorage for prolonged accessibility. However, ...

Iframe not displaying Base64 encoded PDF in Chrome App

Currently, I am in the process of developing a Chrome App that essentially acts as a wrapper for the main app within a webview. The webview sends a Base64 encoded PDF as a message to the app, which then creates a hidden iframe and loads the PDF into the fr ...

Error: Node.js exceeds maximum call stack size while inspecting an objectlogging or debugging

After defining a class as shown below, I encountered an error stating RangeError: Maximum call stack size exceeded when attempting to review the properties of the Object. var Individual = (function () { function Individual(name, age) { this.na ...

Accessing values from an array within a JSON object using jqGrid

Here is an example of my JSON data: [{"codDiretor":"123", "nomeDiretor":"Nome do Diretor", "data":"29/01/2014", "documentos":[{"codDocumento":"1", "nomeDocumento":"Primeiro Doc"}, {"codDocumento":"2","nomeDocumento":"Segundo Doc"}] ...

View a specific selected newsAPI article on its own dedicated page

I have been working on a news website and successfully displayed all the articles on a single page using the news API in nodeJs. Everything is functioning well, but now I want to show the clicked article on a separate page. Although I managed to route it t ...

Can someone please help me convert this jQuery code into vanilla JavaScript?

My Cordova app has an email sending function that utilizes jQuery. During debugging, the ajax function works perfectly in my browser, but once I build the app and test it on my phone, it stops working. I encountered a similar issue before, which was resolv ...

What causes a globally declared array to remain empty in the global scope even after data is pushed to it within a callback function?

Initially, I set an empty array as the value for the global variable artistURLs. Then, within the Cheerio .each() iterator method, I push strings (stored in the local variable artistURL) into the artistURLs array. var request = require('request&apos ...