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

Using regular expressions in Javascript to extract decimal numbers from a string for mathematical operations

I'm currently working on a Vue method where I extract information from a WordPress database. The data retrieved sometimes contains unnecessary text that I want to filter out. Using the prodInfo variable, the input data looks something like this: 2,5k ...

Is it feasible to execute exe files within a ReactJS environment?

Hey there! I've created a Game Launcher using ReactJS for my Unity game and was wondering if it's feasible to start the game (an exe file) simply by clicking on the play button. Can anyone please advise me on this? ...

Discovering the status of a wrapped component using Jest

const wrapper = mount( <ContextProvider> <FreeformEquationQuestionPractice question={question} /> </ContextProvider> ) console.log('freeform state: ', wrapper.childAt(0).instance().state) FreeformEquationQues ...

Tips for checking the validity of PHP variable names, such as $as['abc'], within an HTML textbox

Can anyone assist me with validating a user input PHP variable name such as $as_cap['abc'] during insertion? I need to verify if the format of the variable name is correct or incorrect. Currently, I am using eregi("^[a-z0-9_.'-]{1,50}$") ...

The Dropzone feature fails to function properly when displayed on a modal window that is being shown via

After attempting to integrate Dropzone and JavaScript into a Bootstrap Modal called through AJAX, I encountered issues. Due to the high number of records, I avoided placing the Modal in a foreach loop and instead used AJAX to call a controller method upon ...

When utilizing a wrapped v-text-field, it triggers warning messages and fails to update the data properly

Recently delving into the world of vue.js, I've been experimenting with creating a form using Vue, vuetify, and vuelidate. Oddly enough, when I don't wrap the v-text-field there are no issues, but as soon as I try to encapsulate it within compone ...

Creating a sticky footer using Vue.js for both mobile and desktop display views

Looking for a solution to create a sticky footer that works on both desktop and mobile views without overlapping the main content? The current code either overlaps or doesn't stick to the bottom. Seeking a responsive approach. App.vue: <template& ...

Manually controlling line breaks in HTML text

When collaborating with designers, they often have strong opinions about word wrapping in the final HTML page. If I am working on a fixed layout (non-responsive) and the designer is not satisfied with how the text wraps, there are several options available ...

Retrieve elements from a separate pom file

I am looking to organize my web elements by defining them in a separate js file from my test file using Protractor. In my pom.js object, I have set up the following: let web_elements = function() { this.get_login_mail, function() { ...

Troubleshooting Material-UI: The Mystery of the Missing Dialog

I have been struggling with getting a pop-up dialog to appear when a form is incorrectly filled out. Despite my efforts, the code that should trigger the dialog upon submission does not seem to be working as expected. The function renderError(), responsib ...

Dealing with scenarios where the DOM undergoes changes that overwrite certain variables

I am currently using Ruby on Rails, jQuery version 1.8.3, and jQuery UI version 1.9.2 within my project. Within a view file, I have implemented the rendering of a partial template in the following manner: <%= render :partial => 'template_name&a ...

Encountering an issue: Integrating JSON data into HTML using Angular.JS!

Having trouble transferring JSON data to HTML using Angular.JS for a programming course. The author doesn't seem to have this issue, can anyone provide some assistance? I've correctly linked Angular and added the app, but it's not working a ...

React testing with Mocha experiencing an Invariant violation

Currently, I am in the process of setting up a React project using Electron. Lately, I have been experimenting with configuring Mocha as my test framework. Everything seems to be working fine when I run: "test": "mocha -w --require babel-core/register ...

Error in TypeScript when using Google Maps React with Next.js: there is a possibility that infoWindow.close is undefined

Working on a small project in next.js (typescript) utilizing the google maps api with a KmlLayer. I want my map to interact with another component, SensorInfo. The current setup allows for smooth interaction between them - when SensorInfo is closed, the in ...

Require modifying the radio button's value based on the presence of a certain class in an input field

Feeling overwhelmed. I am currently working on implementing a credit card auto system using the Stripe Payment plugin, but I find myself at a loss. Specifically, when a MasterCard is entered in the card number input field, it should receive the "masterca ...

What scenarios call for utilizing "dangerouslySetInnerHTML" in my React code?

I am struggling to grasp the concept of when and why to use the term "dangerous," especially since many programmers incorporate it into their codes. I require clarification on the appropriate usage and still have difficulty understanding, as my exposure ha ...

I'm a bit uncertain about the best placement for my progress bar component during the API call

Trying to grasp material ui I managed to implement the progress bar. Struggling with loading it until my data is fully loaded. Uncertain about where to place my progress bar component. Could you guide me on how to resolve this issue during API calls, so I ...

The GridFS/multer module is encountering an issue where it is unable to access the 'filename' property of an undefined

My knowledge in web development is limited, so forgive me if this question seems naive. The issue I am facing involves Node.Js and the creation of a database to store and display images on a browser using an .ejs file. While I can successfully log the im ...

Error message: Unable to assign value to 'kind' property as it is undefined in Angular Webpack application

Unexpectedly, my Angular application is encountering an error during the build process. TypeError: C:\Users\c\dev\privacy\node_modules\@fortawesome\angular-fontawesome\fesm2020\angular-fontawesome.mjs: Cannot se ...

Error message: Unable to access $controller with AngularJS and Karma

As someone who is just starting with testing, I figured it was a good idea to begin testing this project. However, when I execute grunt karma:watch, I encounter an error related to the configuration files. My config file includes: module.exports = functi ...