ensure that only one option can be selected with the checkbox

Can someone help me with applying this code on VueJS? I tried replacing onclick with @click but it's not working for me. I'm new to VueJS, so any guidance would be appreciated!

function onlyOne(checkbox) {
    var checkboxes = document.getElementsByName('check')
    checkboxes.forEach((item) => {
        if (item !== checkbox) item.checked = false
    })
}
<input type="checkbox" name="check" onclick="onlyOne(this)">
<input type="checkbox" name="check" onclick="onlyOne(this)">
<input type="checkbox" name="check" onclick="onlyOne(this)">
<input type="checkbox" name="check" onclick="onlyOne(this)">

Answer №1

Here is a simple solution to the problem at hand:

new Vue({
  el: "#app",
  data() {
    return {
      checkboxes: [{
          checked: false
        },
        {
          checked: false
        },
        {
          checked: false
        },
        {
          checked: false
        },
      ]
    }
  },
  methods: {
    onChange(cb) {
      this.checkboxes = this.checkboxes.map(checkbox => ({ checked: cb == checkbox }))
    },
  },
  template: `
    <div>
      <div
        v-for="(checkbox, i) in checkboxes"
        :key="i"
      >
        <input
          type="checkbox"
          :checked="checkbox.checked"
          @change="() => onChange(checkbox)"
        />
        {{ checkbox.checked }}
      </div>
    </div>
  `
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app"></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

Is it possible to set a read-only attribute using getElementByName method

To make a text field "readonly" by placing JavaScript code inside an external JS file, the HTML page cannot be directly modified because it is located on a remote server. However, interaction can be done by adding code in an external JS file hosted on a pe ...

The Vuejs Fetch GET Request encounters a failure, despite working flawlessly in Postman and the browser, all thanks to a 302 redirection

In my web application developed with NuxtJS/Vuejs, I have a field where users can input a URL. The application is supposed to make a GET request to that URL and retrieve data, often related to GitHub in either XML or JSON format. However, when I try to pr ...

Having trouble with GSAP CDN not functioning properly in your JavaScript or HTML document?

After watching a tutorial on YouTube by Gary Simon, I attempted to animate text using GSAP. Despite following the instructions meticulously and copying the CDN for GSAP and CSSRulePlugin just like him, nothing seems to be happening. Even setting my border ...

Displaying JavaScript Array Elements in an Aligned Table Format

Unfortunately, I accidentally deleted my previous post and now need to repost it. I have a code that is functioning well, thanks to the great help I received here. However, the output of the array players is not neatly aligned with each other in a table f ...

Sophisticated filter - Conceal Ancestry

Check out this snippet of my HTML: <td> <a class="button" href="#"> <input id="download">...</input> </a> <a class="button" href="#"> <input id="downloadcsv">...</input> </a> </td> I am ...

Ensure history.back() does not trigger Confirm Form Resubmission

Within my web application, every form submission is directed to an action folder. Once the process is complete, the user is redirected back to their original location. However, a problem arises when the user performs an action that requires the application ...

Should I utilize capacitor's geolocation or opt for capacitor-community's background-location?

Currently developing a mobile app using Ionic/Vue 6 that traces the path of hikers. I have reached the stage where GPS information is required, and the challenge is making sure the GPS plugin remains active even when the user keeps their phone in their p ...

swap out a JavaScript function for a fresh function

In our ordering system, there is a hidden function that I cannot access. Interestingly, this function contains a spelling error which causes a grammar issue to appear in a popup when a user interacts with it. Is there any way for me to either modify the t ...

Updating the background of a button with Vue JS by utilizing an object upon clicking

If you have three buttons and want to change the background color when clicked, for example, clicking on the red button should turn the background color red. However, there is an important detail here: if you click on one button and then another, the old c ...

Transforming JSON date format to a different one using Jackson libraries

My spring boot 1.3.5 application is using jackson with the dependency "com.fasterxml.jackson.datatype:jackson-datatype-jsr310:2.5.0". Encountering an issue when a user inputs a date value in a format different than expected (mm/dd/yyyy) during a POST requ ...

Generate interactive tables using data from an XML file

Hello, I'm in the process of generating tables from an XML file using Node.js with the Express framework. I am utilizing npm modules xmldom and xmldoc for this task. The objective is to present these data tables on an ejs page. Here is the structure ...

Strange anomalies arising in frontend Apollo and GraphQL integration

Currently, I am working with nuxt.js and apollo. One issue I am facing is that when I click a button, it sends a request to the graphql server. The strange part is that the first time I click the button, everything works as expected. However, when I clic ...

Adding an element in real-time to a sortable list item using VueJs

I'm working on a project with a sortable list and I have two main goals: To be able to add/remove LI elements from the list using a +/- symbol. The list includes a textarea with data - my challenge is storing this data properly when adding or removin ...

JavaScript - I have a variable trapped inside a function and I'm struggling to retrieve it

Is it possible that I'm missing something obvious here? I am really struggling to pass the 'body' variable out of this nested function. function retrieveFacebookInfo(userID) { request({ "url": "https://graph.facebook.com/v2.6/" + ...

What is the method for setting the doctype to HTML in JavaScript or React?

I created a canvas with a height equal to window.innerHeight, but unexpectedly it seems to have 100% screen height plus an extra 4 pixels coming from somewhere. I came across a solution suggesting that I need to declare doctype html, but I'm unsure ho ...

Utilizing multiple language files in Vue with vue-i18n: A comprehensive guide

Recently delving into vue and utilizing vuetify for my project, I managed to incorporate internationalization successfully. However, I am encountering difficulties with the standard method of a single file per language as my project expands, making maint ...

Loading Bootstrap accordion content with AJAX only when clicked

Is there a way to load ajax content into an accordion only when it is active? This could help prevent unnecessary data loading. It would be helpful to have a spinner displayed while the content is loading. I've searched online but haven't found a ...

Incorporating a requirement into a function to ensure it is executed only under certain circumstances

I'm currently developing a text-based game using JavaScript that involves picking up a sword with the help of an in-game function. var takeSword = function() { if (currentRoom.hasSword) { $("<p>You picked up a sword.</p&g ...

Troubleshooting problems with Bootstrap datepicker in a Vue project

I am facing a problem with the b-datepicker feature while trying to select a date. The dates are not appearing correctly, as shown in the image linked below. Here is my code: <b-form-group class="my-3" > <b-input-group> ...