Engage the switch on each button individually

Here is a snippet of code I found on Bootstrap's website:

<template>
<div>
  <b-button-group size="sm">
    <b-button
      v-for="(btn, idx) in buttons"
      :key="idx"
      :pressed.sync="btn.state"
      variant="primary"
    >
      {{ btn.caption }}
    </b-button>
  </b-button-group>
  <p>Pressed States: <strong>{{ btnStates }}</strong></p>
</div>
</template>

<script>
export default {
  data() {
    return {
      buttons: [
        { caption: 'Toggle 1', state: true },
        { caption: 'Toggle 2', state: false },
        { caption: 'Toggle 3', state: false },
        { caption: 'Toggle 4', state: false }
      ]
    }
  },
  computed: {
    btnStates() {
      return this.buttons.map(btn => btn.state)
    }
  }
}
</script>

I want to modify the toggle functionality so that only one button can be active at a time. When you click on a button, it should become true, but if there are others already set as true, they should become false. In other words, only one button should be active. However, I'm facing an issue where the focus shifts away when clicking elsewhere on the screen, making the toggling not as effective.

Answer №1

To implement a unique functionality for only one button, you can utilize a click event handler that leverages the index of the clicked button. This handler will unpress all other buttons in the group.

<b-button
   v-for="(btn, idx) in buttons"
   :key="idx"
   :pressed.sync="btn.state"
   variant="primary"
   @click="onPress(idx)"
>
methods: {
  onPress(i) {
    this.buttons.forEach((b, index) => b.state = i === index)
  }
}

It's important to note that losing focus does not alter the pressed state of any button; it simply removes the visual focus border.

https://i.sstatic.net/u1mH9.gif

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 timing of the RequestAnimationFrame function varies based on the dimensions of my canvas

In my application, I have a canvas that dynamically adjusts its CSS size based on the window size. The main gameplay loop in my code looks like this: run = function(){ console.log(timerDiff(frameTime)); game.inputManage(); game.logics(); ...

How can I bold just a single part of a string in VueJS?

I'm trying to figure out how to make a specific number within a string of text bold in Vue.js. Is there an easy way to achieve this? <a :href="detailUrl"> {{ content }} <span v-if="detailText && detailUrl" ...

Create a form with Vue that generates input fields based on JSON data and

I am seeking assistance with implementing a truncate filter for vueformulate in my project. I am generating the form from json data and need to limit the label to 80 characters, with a read more/less option. The data is dynamic, so changing the label in th ...

JQuery script is malfunctioning

My community website is set up as shown below: <div id="posts"> <div class="container"> <div id="placeholder"></div> <h1>Friend Requests</h1> </div> </div> getRequests.js appends the ...

React-select: issue with maintaining selected option on input

Hello everyone, I am new to React and seeking some assistance in reviewing my code. I have a component called Bucket that contains multiple challenges as separate components. Here is a simplified version of the code: class CLL_Bucket extends Component { ...

Attempting to iterate over an array and utilize a foreach loop to return several sets of data

In my original code, getProductInfo took two parameters (res, sku). However, I now want to pass a set object containing SKU numbers and for each SKU, send the data using res.send. const activeProductBank = new Set([6401728, 6430161, 6359222, 6368084]); g ...

What is the best way to conceal a dropdown menu when the page first loads?

I have a dropdown menu that is displaying like this: <ul> <li class="dropdown open"> <a aria-expanded="true" href="#" class="dropdown-toggle waves-effect waves-button waves-classic" data-toggle="dropdown"> <spa ...

Utilizing Vue 3 props validation in conjunction with the power of Typescript

Looking to customize a Link component using Nuxt, Typescript, and the composition-api. The prop target can accept specific values as outlined below. I'm curious if using a custom validator function to check prop types at runtime adds value when compar ...

I would like to have text show up instead of an alert when validation is triggered

Hey there, I need some help with JavaScript as I'm just getting started. Basically, I want to display the text "please fill in" next to a textbox if the user hasn't entered any information. <!DOCTYPE html> <head> <title>Easy ...

Transitioning code from gatsby to nextjs has caused an issue with the aws-sdk integration

I have successfully integrated the aws-sdk with Gatsby by using a .env file to upload a file to an S3 bucket. Now, I am in the process of migrating this functionality to Next.js, but I'm encountering an error in Next.js. Uncaught (in promise) Credent ...

Incorporating various language URLs in Next.js using next-i18n-next functionality

Thinking about using the next-i18next internationalization library. Check out next-i18next on GitHub Curious about how to change the language in the path of my URL. For example: /about-us /over-ons -> takes you to the Dutch version of the about us p ...

Rendering a Pop-up for a Single Array Item Retrieved from an API in ReactJS

Apologies if my wording is unclear, this is my first question, and I'm relatively new to JS/React... I have successfully mapped through an array from an API call and displayed the necessary information. How can I display a popup for a single element ...

What is the best way to generate the message dynamically?

I have implemented the react-intl package for translation purposes in my project. Users have the option to choose between Spanish and English languages, with Spanish being the default language. When a user switches to English, all text should be dynamicall ...

When attempting to post data using jQuery, an object is encountered that does not have a parameterless constructor

Here is the code snippet I am using with jQuery to post data and register a band: var formData = new FormData(); var file = document.getElementById("CoverPicture").files[0]; formData.append("file", file); var Name = $('#Name').val(); var Genre = ...

Can Big Data flow on Mongo DB be effectively simulated?

My idea involves creating a server with routes and models to be hosted on Heroku for processing requests. I plan to make incremental requests to the server until they qualify as Big Data. I suspect there may be limitations on how many consecutive requests ...

What is the best way to efficiently execute a function multiple times and ensure each call is completed before the next

Currently utilizing node.js I have a function that requires multiple parameters to be called inside a loop. It is crucial for the function to be called with the loop iterator as one of its parameters and waiting for it to finish processing before calling ...

Locate a JQuery element within another JQuery element

Apologies for my poor grasp of English. I am working with HTML and JavaScript. <noindex> <h1>This is h1 in noindex</h1> <div> <h1>This is h1 in noindex and in div</h1> <div> <h1>This is h1 in noindex a ...

Error caused by Vue bootstrap-vue following installation

I'm facing an issue after adding Bootstrap Vue to a new project. The error message that pops up is related to a syntax error in the App.vue file. Has anyone encountered this before and knows how to fix it? Failed to compile with 1 error 11:44:32 er ...

The clear function in the template slot of Vue multiselect is not functioning properly

I decided to incorporate the asynchronous select feature found in the documentation for my project. This feature allows me to easily remove a selected value by clicking on 'X'. Below is a snippet of the general component that I use across variou ...

Using URL parameters with Select2

Currently, I am in the process of setting up tagging and utilizing ajax to display the most commonly used tags. To accomplish this, I decided to employ the Select2 plugin. However, I encountered a roadblock when attempting to retrieve my JSON Data in my ja ...