Generate radio buttons in a model loop in Vue.js based on names automatically

I am attempting to generate a model for each radio button using the inputname as the identifier. My approach involves looping through the array of objects to identify instances where more than one inputname is present, and then converting this value into an object property for the models. However, I am encountering difficulties in executing these steps.

<script>
export default {
    data(){
      return{
      options: [
        {
          name: 'Radio2',
          price: '100',
          inputname: 'rady',
          option_type: 'radio'
        },
        {
          name: 'Radio1',
          price: '50',
          inputname: 'rady',
          option_type: 'radio'
        },
        {
          name: 'Radio2',
          price: '50',
          inputname: 'brady',
          option_type: 'radio'
        },
        {
          name: 'Radio1',
          price: '50',
          inputname: 'brady',
          option_type: 'radio'
        },

      ],
      radioButtons: []
      }
    },
    created(){
    
     var valueArr = this.options.map(function(item){ 
      this.radioButtons.push({ value: ''+ item.inputname +'' });
        //return item.inputname 
        });
      console.log(valueArr)
      console.log(this.radioButtons)
 
    
    
    }
}
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<template>
<div>
        <div v-if="option.option_type == 'radio'">

          <b-form-radio v-model="radioButtons"  :name="option.inputname" :value="option">
            {{option.name}}--- {{option.price}}
          </b-form-radio>

        </div>

</div>

</template>

Answer №1

Are you aiming for this specific outcome?

new Vue({
  el: '#app',

  data(){
    return{
      options: [
        {
          name: 'Option A',
          price: '50',
          inputname: 'optA',
          option_type: 'checkbox'
        },
        {
          name: 'Option B',
          price: '75',
          inputname: 'optB',
          option_type: 'checkbox'
        },
        {
          name: 'Option C',
          price: '100',
          inputname: 'optC',
          option_type: 'checkbox'
        },
      ],
      
      selected_options: {},
    }
  },

  computed: {
    checkboxGroups() {
      const obj = {};
      
      this.options.forEach(option => {
        if (option.option_type === 'checkbox') {
          if (!obj[option.inputname]) {
            obj[option.inputname] = [];
          }
          
          obj[option.inputname].push({name: option.name, value: option.price})
        }
      })
      
      return Object.entries(obj).map(([key, value]) => {
        return {
          label: key,
          items: value,
        }
      })
    }
  },
})
<link type="text/css" rel="stylesheet" href="//unpkg.com/bootstrap/dist/css/bootstrap.min.css" />
<link type="text/css" rel="stylesheet" href="//unpkg.com/bootstrap-vue@latest/dist/bootstrap-vue.min.css" />

<script src="//polyfill.io/v3/polyfill.min.js?features=es2015%2CIntersectionObserver" crossorigin="anonymous"></script>

<script src="//unpkg.com/vue@latest/dist/vue.min.js"></script>
<script src="//unpkg.com/bootstrap-vue@latest/dist/bootstrap-vue.min.js"></script>

<script src="//unpkg.com/bootstrap-vue@latest/dist/bootstrap-vue-icons.min.js"></script>

<div id='app'>
  <b-form-group v-for="checkboxGroup in checkboxGroups" :label="checkboxGroup.label">
    <b-form-checkbox v-for="item in checkboxGroup.items" v-model="selected_options[checkboxGroup.label]" :name="checkboxGroup.label + item.name" :value="item.value">
     {{ item.name }} - {{ item.value }}
    </b-form-checkbox>
  </b-form-group>
  
  {{ selected_options }}
</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

JavaScript salary calculation function not functioning properly

Once the user inputs the employee's name and the number of hours they worked on the HTML form, the submit button captures this information and stores it in variables for calculating their pay. The script also factors in overtime pay. Despite feeling l ...

The parameter in a JavaScript for loop

I'm struggling with my Javascript skills. Here is the code snippet I am currently working with: var information = [ {"Column":"","keyw":"","Column_3":"day of march 2011 to someother numeric" ...

Searching for information in a text file and saving it to arrays in C

I am currently facing a challenge where I need to read a text file that includes both strings and numbers, and then store them in separate arrays. The text in the file looks like this: Ryan, Elizabeth 62 McIntyre, Osborne 84 DuMond, Kristin 18 L ...

Using a vuejs mixin with an undefined property being passed as a prop

I recently encountered an issue where attempting to pass a prop to a mixin resulted in a Cannot read property of undefined error. Can anyone provide guidance on how to resolve this issue? The code for my mixin, located in mixins/BarMixin.js, is as follows ...

Ways to extract the value from a jQuery object

How can I retrieve the selected time value using a jQuery plugin and save it on a specific input element within the page? Refer to the plugin and code provided below: http://jsfiddle.net/weareoutman/YkvK9/ var input = $('#input-a'); input.cloc ...

Encountering an issue while implementing a fresh design using Material-UI Version 5 and React Version 18.01 - Specifically facing problems with the '@mui/styles' package

Hi there! I am currently working with react V.18.01 and Material-ui v.5 for my application development, but encountered an error that I need assistance with. Being a beginner developer, I would greatly appreciate a code review to help me understand the iss ...

Retrieving data from a nested array within an array of objects using JavaScript

Below is an example of an array object: const data = [ { name: "A", values: [ { name: "PASS", value: 36, }, ], }, { name: "B", values: [ { ...

Display the title when the mouse hovers over

I am currently working on a minimalist portfolio site where I showcase various projects through images on the landing page. As I iterate over all the projects using {projects.map(({ id, title, route, src }, index) => ())}, I encountered an issue with di ...

The Nest.js Inject decorator is not compatible with property-based injection

I am facing an issue with injecting a dependency into an exception filter. Here is the dependency in question: @Injectable() export class CustomService { constructor() {} async performAction() { console.log('Custom service action executed ...

Guide to resolving domain names in express.js

I've been working on an expressJS script that includes a mongoDB fetch. My objective is to create an API that displays my JSON-based test list on the /api/testlist route. When I try to access the index page, everything seems to be working fine. Howev ...

Unable to bring in the Firebase Firestore Colletion

When working on my next app, I encountered an error while trying to call a Firestore Collection. The specific error message that appeared when I ran the app was: FirebaseError: Firebase: Firebase App named '[DEFAULT]' already exists (app/duplicat ...

Endless [React Native] onFlatList onEndReached callback invoked

Attempting to create my debut app using ReactNative with Expo, I've hit a snag with FlatList. The components are making infinite calls even when I'm not at the end of the view. Another issue might be related; across multiple screens, the infinite ...

Generate a fresh FileReader instance using the downloaded file via XmlHTTPRequest

I am attempting to use an XmlHTTPRequest object (level 2) downloaded through a "GET" request in order to create a new FileReader object. My goal is to create the FileReader object within the onload function of the xhr. The file, which is a .gz file, downl ...

The tree expansion does not activate the CSS transition

Currently, I am in the process of creating a TreeView using only CSS and JS. My goal is to include a subtle transition effect when expanding or collapsing a node. The transition effects are successfully implemented for collapsing nodes, however, they do no ...

After diligently following every step on OneCheckout and getting no response when placing an order, I decided to upgrade my Magento version from 1.6.1.0 to 1.8

After upgrading the Magento version from 1.6.1.0 to 1.8.0, everything seems to be working smoothly. However, customers are facing an issue during checkout where they can't actually place their order. Despite following all the steps correctly, when t ...

Ensure that the jQuery datepicker is set with a maximum range of 365 days between the two input fields

Setting Up jQuery Datepicker Inputs I have implemented two jQuery datepicker inputs with default settings as shown below: $("#polis_date_from").datepicker({ uiLibrary: "bootstrap4", changeYear: true, changeMonth: true, dateFormat: "yy.mm.dd", ...

nodejs - pkg encountered an error: only one entry file or directory should be specified

I am currently facing issues with packing my simple cli node script using pkg. After running the command below: host:~ dev$ pkg /Users/dev/Desktop/myscript/ --target node14-macos-x64 node14-linux-x64 node14-win-x64 I encountered an error in the terminal: ...

Tips and tricks for showing a loading gif using the Vue 3 composition api

I just started learning about vue and I'm trying to incorporate a loading gif while waiting for the endpoint to return. I attempted to use watchEffect, but I'm having trouble understanding it. Can someone please clarify if this is the correct ap ...

"Exploring the best way to loop through multiple JSON data in a jQuery response

https://i.stack.imgur.com/O0F6g.pngMy JSON response contains multiple data points presented as follows. WellNames […] 0 {…} id 56 well_name AL HALL api 34005205550000 1 {…} id 498 well_name BONTRAGER api 34005233850000 2 {…} id 499 ...

What is the option for receiving automatic suggestions while formatting components in a react.js file?

When styling elements in our app using app.css or styles.css, VS Code provides auto-suggestions. For example, if we type just "back" for background color, it will suggest completions. However, this feature does not work in react.js or index.js. Why is that ...