Using v-on:click to dynamically update multiple sections of content in a Vue.js and Liquid environment

Whenever I click on a button, I want the text and image to change. I attempted to do this but encountered difficulties in updating multiple elements simultaneously.

{% for variant in product.variants %}
<label for="variant_{{- variant.id }}">{{ variant.title }} - <img src="{{ variant.image | img_url: '100x100' }}" v-on:click="changeMessage('{{ variant.price | money_with_currency }}')"></label>
<input type="radio" {% if forloop.first %}checked{% endif %} class="variant_id" id="variant_{{- variant.id }}" name="productVariants" value="{{ variant.id }}"/>

<div class="variant_price d-none">{{ variant.price | money_with_currency }}</div>
<div class="variant_sku d-none">{{ variant.sku }}</div>
<div class="variant_img d-none">{{ variant.image | img_url: master }}</div>
{% endfor %}

{% raw %}{{ price }}{% endraw %}
{% raw %}{{ image }}{% endraw %}

View Current Store Appearance

The price is currently hidden by default and only appears when I click the radio button. I would like it to be visible by default.

This is how it looks after clicking the radio button

export default {
  data () {
    return {
       price: document.getElementsByClassName('variant_price').innerHTML,
       sku: document.getElementsByClassName('variant_sku').innerHTML,
       img: document.getElementsByClassName('variant_img').innerHTML,
    }
  },
  methods:  {
    changeMessage(message) {
      this.message = message
    }
  },
}

When the radio button is clicked, I want to display the price and image, but my JavaScript skills are lacking. I need assistance, please 🙏🙏🙏

Answer №1

Consider utilizing the mounted() lifecycle hook to establish your initial values.

export default {
  data () {
    return {
       price: document.getElementsByClassName('variant_price').innerHTML,
       sku: document.getElementsByClassName('variant_sku').innerHTML,
       img: document.getElementsByClassName('variant_img').innerHTML,
    }
  },
  mounted(){
    // Set defaults using mounted hook
    this.changeMessage(message);  
  }
  methods:  {
    changeMessage(message) {
      this.message = message
    }
  },
}

Furthermore, could you provide more context or details so that I can offer further assistance?

Answer №2

If you want to modify another element by clicking a button in Vue.js, you need to assign a reference parameter ref="nameOfRef" to those elements. Then, you can access them within the method called by v-on:click using this.$refs.nameOfRef

For example:

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

    <main id="vue-app">
      
      <div ref="div">Hello world</div>
      <button type="button" v-on:click="hideElements()">Hide!</button>
      <button type="button" v-on:click="showElements()">Show!</button>
        
    </main>

<script>
    var app = new Vue({
        el: "#vue-app",
        methods: {

            hideElements: function () {
                this.$refs.div.style.display = "none";
            },
            showElements: function () {
                this.$refs.div.style.display = "inherit";
                
            }
        }
    });
</script>

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

The result after calling JSON.parse(...) was not accurate

The following method is used in the controller: @RequestMapping(value = "channelIntentionDetails.html", method = RequestMethod.POST) public @ResponseBody Report getChannelIntentionDetails(@RequestBody SearchParameters searchParameters) { LOGGER.in ...

The unusual phenomenon of Chromium inexplicably almost freezing in a particular pattern

I am currently using a Raspberry PI 3B+ with raspbian to run my NodeJS (node-red) backend application, which also hosts a frontend application (VueJS) on a 7" display. The main purpose of this setup is to visual maps of 433 Mhz electrical switches within m ...

Display identical text using JavaScript filter

My search filter highlight is currently displaying [object Object] instead of <mark>match values</mark> when replacing the values. This is the code I am using: this.countries.response.filter((val) => { const position = val.value.toLowerCa ...

What is the best way to display changing session variables in PHP?

Purchase Page: This page allows customers to select business card orders in various foreign languages and customize their options. Whenever a user decides to add an extra card by clicking a button, javaScript dynamically includes new form fields. To ensur ...

Ways to conceal an element in Angular based on the truth of one of two conditions

Is there a way to hide an element in Angular if a specific condition is true? I attempted using *ngIf="productID == category.Lane || productID == category.Val", but it did not work as expected. <label>ProductID</label> <ng-select ...

Invoking a Directive within another Directive

Feel free to check out this demo on Plunkr. I've set up a basic structure: <body ng-app="myApp"> <div ng-controller="myController"> <parent-directive></parent-directive> <child-directive></child-direc ...

What is the method for calling a function in a JavaScript file?

I am facing a challenge with reinitializing a JavaScript file named AppForm.js after a successful ajax post response. Within the file, there are various components: (function(namespace, $) { "use strict"; var AppForm = function() { // Cr ...

Regular Expression for jQuery to match both letters and numbers, including special characters

Is there a way to validate text input using a jquery regex that includes specific characters such as A-Z, a-z, 0-9, !, #, $, £ (preferably all currency characters), %, &, -, and _? If so, how can this be implemented? I have attempted to use the regex pa ...

Set tab navigation widget with a fixed height

I am struggling with setting a fixed height for my tabs widget so that when I add more content, it will display a scrollbar instead of expanding endlessly. I have checked the CSS and JS files but cannot figure it out. It is important for me to contain this ...

Tips for updating ng-repeat when the modal is closed?

Scenario: I've got a page (angular) containing a repeater. <tr ng-repeat="row in results.leads"> <td>{{row.SubmittedByName}}</td> Inside the repeater, there's a button in a column that triggers a modal to modify the data o ...

Extract information from Firebase and display it in a React component

I am trying to extract and display data retrieved in componentDidMount. Here is the state setup: constructor(props) { super(props); this.state = { loading: true, data: [] } } and here is the componentDidMount function: compo ...

When you try to click outside of react-select, the dropdown doesn't

I've been working on customizing react-select and encountered some issues. Specifically, after modifying the ValueContainer and SelectContainer components, I noticed that the dropdown doesn't close when clicking outside of it after selecting a va ...

Capturing an image of an HTML5 canvas that includes an image object: tips and tricks

After creating a canvas and adding various objects like images, clipart, and text to it, I encountered an issue. When capturing a snapshot of the canvas with only text using the method `canvas.toDataURL()`, the snap is correct. However, when I include an i ...

Having difficulty in selecting the element

My current challenge involves using Appium to automate a framework I've created. After inspecting an element with Appium inspector, I'm attempting to click on the element within the DOM, even though it's not visible on the device screen. I t ...

Creating pagination using AJAX to fetch data from an API while maintaining the same query parameters

Writing a title for this may be a bit tricky, but I'll try my best. On the webpage located at the /music-maker endpoint, there is a modal that contains an input field. This input field captures user input and sends it to the backend using AJAX. The u ...

Looking to transform an HTML table into a stylish CSS layout complete with a form submission button?

Recently, I've been delving into the world of CSS and PHP as I work on converting old code entirely into HTML and PHP with a touch of CSS. The visual aspect seems fine, but I've hit a roadblock with the submit form due to an IF statement in PHP. ...

What are the steps for scheduling asynchronous tasks using Promises in Node.js?

As a beginner in Javascript, I am struggling to understand how to execute my functions sequentially. My goal is to use Promises to accomplish this task. I am currently following a tutorial on creating a chat bot for Facebook Messenger. Essentially, I want ...

Utilizing THREE.JS Raycaster with JavaScript "entities" rather than just meshes

I am facing a challenge with the Raycaster model. I grasp the concept of how it intersects meshes that can be transformed, but my issue lies in identifying when the specific instance of an object is clicked. Consider a scenario where there is a button. Th ...

Is this the correct method for linking the function to every individual element?

Is it correct to attach the function to each element individually? Also, is my function correctly implemented? <ul id='forShopping'> <li><input class='ch' type='checkbox' onclick='isAct ...

Looking to transition from Angular 1.5x to ReactJS, what is the most effective method for conducting A/B tests and exploring different views?

As I transition part of the UI code to ReactJS, I am considering A/B testing my app for instrumentation. I have looked into Intuit's Wasabi as a potential framework but found its setup process in production to be cumbersome. I am seeking an alternativ ...