A guide to setting up checkbox input in Vue 3 so that it toggles between checked and unchecked states when an

I'm in the process of creating a div container that will contain both an image and a checkbox input element. The checkbox input has a click handler that passes a value to a function, as well as a :value binding which sends the value to an array named checkBoxArray. Additionally, I am using v-model=checkBoxArray to automatically check the checkbox if the array contains the specified value. My goal is to make it possible for users to also click on the accompanying image to toggle the checkbox's state, but simply adding a click handler to the image alone doesn't seem to be doing the trick. How can I implement a click handler on the image element to control the checkbox as well?

Below is my current code:

          <div v-for="item in items" :key="item.id">
            <span class="flex-1 flex">
              <span class="flex flex-col mr-4 mt-16">
                <input v-model="checkBoxArray" :value="item.id" @click="someFunction(item.id)" type="checkbox" class="h-5 w-5" />
              </span>
              <span class="flex flex-col">
                <img @click="someFunction(item.id)" class="h-full w-full" :src="item.image_url" alt="" />
              </span>
            </span>
          </div>

const checkBoxArray = ref([])

Answer №1

It appears that the solution you provided may be modified slightly, as shown in the snippet below:

const { ref } = Vue
const app = Vue.createApp({
  setup() {
    const checkBoxItems = ref([])
    const sampleItems = [{id: 0, image_url: 'https://example.com/image_0'}, {id: 1, image_url: 'https://example.com/image_1'}]
    const toggleFunction = (id) => {
      checkBoxItems.value[id] = !checkBoxItems.value[id]
      console.log(id)
    }
    return {
      checkBoxItems, sampleItems, toggleFunction
    };
  },
})
app.mount('#demo')
<script src="https://unpkg.com/vue@3/dist/vue.global.prod.js"></script>
<div id="demo">
  <div v-for="item in sampleItems" :key="item.id">
    <span class="flex-1 flex">
      <span class="flex flex-col mr-4 mt-16">
        <input v-model="checkBoxItems[item.id]" @click="toggleFunction(item.id)" type="checkbox" class="h-5 w-5" />
      </span>
      <span class="flex flex-col">
        <img @click="toggleFunction(item.id)" class="h-full w-full" :src="item.image_url" alt="" />
      </span>
    </span>
{{checkBoxItems}}
  </div>
</div>

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

Issue with VueJS where changes made to properties in the mounted hook do not properly trigger the

I'm working on a VueJS component that features a button with computed properties for its class and text. These properties change every time the button is clicked, updating smoothly with each interaction. However, I've encountered an issue when at ...

What is the best way to display a component based on the route using GatsbyJS?

Currently working with GatsbyJS and attempting to dynamically render different header components based on the URL route. For instance: mydomain.com/ should display HeaderLanding mydomain.com/blog should display HeaderMain Seeking guidance on how to imp ...

Get all inputs with the same text using Vue 3 composition API and a single ref, or access multiple inputs with the

One of the challenges I'm facing is managing multiple instances of a component called InputWithValidation within a form. I need to check if all instances are valid at once. For a single instance of InputWithValidation, I can easily verify its validit ...

Theme.breakpoints.down not being acknowledged by MUI breakpoints

The Challenge: Implement a hamburger menu to replace the navMenu on tablet and smaller screens After successfully compiling in VS code terminal, encountering an error in the browser: Error Message: TypeError: Cannot read properties of undefined (reading ...

Tips for revealing a position: absolute div that is currently hidden with display: none styling

Below is the code for a div element that I want to temporarily hide using JavaScript: <div id="mydiv" style="position: absolute; top: 60px; left:5px; right:25px; bottom:10px;"> </div> After hiding it with display:none in my ...

Flow object with Angular using ng-flow: Existing flow object

Just a quick question that I can't seem to find an answer for on my own or through searching online. Currently, I have a button set up for clicking and uploading files. However, I also want to incorporate drag and drop functionality using the same fra ...

Is it normal for my sweelart2 to consistently be positioned behind my v-dialog component in Vuetify 3?

Why does my sweetalert2 always appear behind my v-dialog in Vuetify3? Can anyone assist me with resolving this issue? I have tried various alternatives for sweetalert2 but have not found a solution yet. Whenever I use sweetalert with v-dialog, the sweetal ...

Content obscuring dropdown menu

I am currently working on a screen design that resembles the following: return ( <SafeAreaView> <View style={styles.container}> <View style={styles.topContainer}> <View style={styles.searchFieldContainer}> ...

An issue occurred while serializing or deserializing, specifically with the JavaScriptSerializer and

I am facing an issue while trying to retrieve images from my database. The process works smoothly with small images, but when attempting to do the same with the default Windows 7 images (Desert, Koala, Penguins, Tulips, etc.), I encounter an error: "Err ...

What is the hierarchy for displaying elements depending on the props?

I have developed a search input component that includes an icon which I want to reposition (either on the left or right side) depending on different scenarios. This input is part of a bootstrap input-group, so modifying the order of elements within my di ...

Modifying a CSS property with jQuery

If I have the following HTML, how can I dynamically adjust the width of all "thinger" divs? ... <div class="thinger">...</div> <div class="thinger">...</div> <div class="thinger">...</div> ... One way to do this is usi ...

Automating the movement of a slider input gradually throughout a specified duration

I am working on a website that includes a range input setup like this: <input type="range" min="1036000000000" max="1510462800000" value="0" class="slider" id ="slider"/> Additionally, I have integrated some D3 code for visualizations. You can view ...

Determining the height of a Bootstrap column in relation to another element

Utilizing the grid layout from bootstrap, I have the following structure: <div id="prof_cont_enclose"> <div class="row"> <div class="prof_cont_row"> <div class="col-xs-12 col-sm-4 col-md-2 col-lg-2 prof_elem"&g ...

Performing AJAX requests to dynamically update multiple DIVs

Encountering difficulties with adding additional input fields to a page, each of which contains jquery code for appending more select boxes related to them. The base html setup is as follows: <p id="add_field"> … </p> <div class="show_sub ...

The impact of a variable in a function with XMLHttpRequest

How does the XMLHttpReqeust variable impact the functionality of the following code snippets? function getHTTPObject() { if (typeof XMLHttpRequest == "undefined") { XMLHttpRequest = function () { try { return new Ac ...

The Add/Remove button functionality is not functioning as expected for duplicated form fields when using jQuery

I am experiencing an issue with the functionality of the "Add another" and "Remove row" buttons in my form. I implemented code from a specific Stack Overflow answer (jquery clone form fields and increment id) to create a cloneable section, but only the ori ...

Minimize unnecessary rendering in React when toggling between tabs

I am currently working on a React application that utilizes material-ui to generate tabs. <div className={classes.root}> <AppBar position="static"> <Tabs value={value} onChange={handleChange}> <Tab label="Item One" /> ...

Creating a dependent picklist feature using node.js and express

I am currently delving into the world of node.js and express. In my node.js application, I am utilizing express along with express-handlebars as the templating framework. My goal is to incorporate a dependent picklist that dynamically renders based on the ...

Building a hierarchical object structure from an array

I am working with an array of objects that looks like this: const sorted = [ { IsoCode: "EUR", Buy: 1.948, Sell: 1.963 }, { IsoCode: "GBP", Buy: 2.1184, Sell: 2.1894 }, { IsoCode: "USD", Buy: 1.5781, Sell: 1.6484 }, ] and my ...

Modify the style of a webpage through JavaScript

Need help with calling a JS event based on button presses and changing CSS font styling accordingly for each button? Check out the code snippet below: body { background-image: url("back2.jpg"); background-size: 100% 100%; } ...