What is the best way to retrieve selected radio button values from multiple radio buttons using Vue.js?

Is there a way to extract the selected value from a group of radio buttons in a form that includes product variants like color and size obtained from the backend? Additionally, how can a validation message be displayed if the form is submitted without selecting a radio button?

<form @submit.prevent="submit">
  <div v-for="(variants, index) in product_details" :key="index">
    <p>
      <b>{{ variants.title }}</b> -
    </p>
    <div
      class="input-group mt-2 increasenumber"
    >
      <div
        class="optionalitem"
        v-for="(detail, index1) in variants.details"
        :key="index1 + variants.title"
      >
        <input
          type="radio"
          :name="variants.title"
          :id="index + '_' + index1"
          class="newoneche"
          :value="detail.value"
        />
        <label :for="index + '_' + index1" class="select01"
          ><p class="highlight"gt;
            {{ detail.name }}
          </p>
        </label>
      </div>
    </div>
  </div>

  <button color="success">Submit</button>
</form>

Script

<script>
export default {
  data() {
    return {
      product_details: [
        {
          title: "Choose Colour",
          details: [
            {
              name: "Red",
              value: "red",
            },
            {
              name: "Green",
              value: "green",
            },
            {
              name: "Yellow",
              value: "yellow",
            },
          ],
        },
        {
          title: "Choose Size",
          details: [
            {
              name: "Small",
              value: "small",
            },
            {
              name: "Large",
              value: "lage",
            },
          ],
        },
      ],
    };
  },
</script>

Answer №1

Perhaps something similar to the code snippet below:

new Vue({
  el:"#demo",
  data() {
    return {
      product_details: [{title: "Color", details: [{name: "Red", value: "red",}, {name: "Green", value: "green",}, {name: "Yellow", value: "yellow",},],}, {title: "Size", details: [{name: "Small", value: "small",},{name: "Large", value: "large",},],},],
      products: [{name: 'Product 1', Color: 'red', Size: 'large'}, {name: 'Product 2', Color: 'green', Size: 'small'}]
    }
  }
})
.cont, .optionalitem, .input-group {
  display: flex;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="demo">
  <div v-for="(product, i) in products" :key="i">
    <h3>{{ product.name }}</h3>
    <form @submit.prevent="submit">
      <div v-for="(variants, index) in product_details" :key="index" class="cont">
        <p><b>Choose {{ variants.title }}</b> - </p>
        <div class="input-group mt-2 increasenumber">
          <div
            class="optionalitem"
            v-for="(detail, index1) in variants.details"
            :key="index1 + variants.title"
          >
            <input
              type="radio"
              :id="index + '_' + index1"
              class="newoneche"
              :value="detail.value"
              v-model="products[i][variants.title]"
            />
            <label :for="index + '_' + index1" class="select01">
              <p class="highlight">
                {{ detail.name }}
              </p>
            </label>
          </div>
        </div>
      </div>
      {{product}}
      <button color="success">Submit</button>
    </form>
  </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

Subscribe on Footer triggers automatic scrolling to the bottom of the page

Whenever I fill out the form in the footer and hit submit, it directs me to a different page while automatically scrolling back down to the footer. I'm looking for a solution that prevents this automatic scrolling. I've attempted using window.sc ...

Integrating new components into JSON data

I started by creating a JSON document in my code using the following syntax: let jsonData = []; To populate this document, I utilized the '.push()' method to add elements in this manner: jsonData.push({type: "example", value: "123"}); Eventua ...

Uncovering the Secrets of Accessing Tag Attributes in ReactJS

I have developed a small app using reactjs. I have set an attribute on the button tag and passed a value to it. Now, when I click on the button, I want to retrieve the attribute value. How can I achieve this with react js? Here is a sample code snippet: ...

Ways to showcase hierarchical list information in tabulator

I have set up a search and listing panel on my screen. To display nested data on the listing page, I decided to use tabulator. Here is the code in my js file : function onCheckClick() { var url = "/SomeController/SomeAction/"; $.ajax({ url: ...

Bug found in React Native when navigating between screens causing the screen size to shrink

Check out the image below. https://i.stack.imgur.com/t04Vv.png Issue: Whenever I switch to a new scene, the previous screen appears to shrink or move upwards. This behavior is not consistent with the usual user experience seen on Apple apps - any thought ...

Each time my classes are initialized, their components undergo reinitialization

Apologies if the question is not well-formed, I am completely new to working with React. I have been attempting to create a dashboard but encountering issues with my states getting reinitialized. Below is the content of my app.js file. import './inde ...

The Mongoose connection status is consistently showing as 0

Utilizing nodejs and mongoose to establish a connection with my MongoDB Database. I am attempting to check the connection state, specifically if it is connected or not. I am using mongoose.connection.readyState to achieve this. The connection seems to be ...

HTML5 failing to load button

<!DOCTYPE html> <html> <head> <title>Greetings Earthlings</title> <script src="HelloWorld.js" /> </head> <body> <button onclick ="pressButton()" >Press Me!</button> ...

Invalidating the express response object due to a TypeError issue

Currently, I am in the process of writing a test that utilizes sinon and sinon-express-mock to mock an incorrect request. The goal is to then call a validation function within my application and verify that it returns the expected response status code (400 ...

The debugger in Google Apps Script freezes when attempting to debug a particular string

I'm facing a perplexing bug that has me stumped. Here's the troublesome code snippet: function testDoubleQuote() { var xmlString = '<file><text>Ehf asor nkles pov ujfemniuea zeïerasvrtrw er Beaetrgfbvcyu Nbv., jei of asverqzs ...

Struggling to understand how to personalize a D3 generated graph

Currently, I am utilizing react-d3 instead of the Plotly react wrapper due to some bugs in the latter. My issue now lies in understanding the d3 API as I am unable to fully grasp it. I have successfully created a scatter plot similar to the one shown on ...

Tips for verifying the contents of a textbox with the help of a Bootstrap

I am still learning javascript and I want to make a banner appear if the textbox is empty, but it's not working. How can I use bootstrap banners to create an alert? <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8&g ...

What is the process for adding content to a JSON object?

I may have a simple question, but I'm new to backend development and I'm trying to figure out how to post in JSON format. Here is the JSON schema I am working with: email: { type: String, unique: true, lowercase: true, required ...

Getting a variable from outside of the observable in Angular - a step-by-step guide

I have an Observable containing an array that I need to extract so I can combine it with another array. this.builderService.getCommercialData() .subscribe( data=>{ this.commercialDetails = data; this.commercialDetailsArr ...

A unique string containing the object element "this.variable" found in a separate file

Snippet of HTML code: <input class="jscolor" id="color-picker"> <div id="rect" class="rect"></div> <script src="jscolor.js"></script> <script src="skrypt.js"></script> Javascript snippet: function up ...

Exploring the power of React's useState and useEffect hooks with JSON data

Just starting out with React. The task I'm tackling involves fetching data from an API (provided in JSON format) and updating the setNavItems with the retrieved JSON response. However, when attempting to iterate over the results using navItems.map, n ...

exploring the similarities between arrays containing nested objects

Can you assist me, please? I need help comparing and calculating the percentage difference between values and returning an array. I have to compare arrays, access objects with names and values, and calculate the percentage. For instance, if the first ite ...

What causes the URL to be undefined after making a JQuery Ajax POST request?

After performing an Ajax Post within a Profile View, I am attempting to refresh the view. Here is the code snippet: $.ajax({ url: '/Profile/Index', dataType: "html", type: "POST", data: JSON.stringify(10), success: ...

JSON parsing in C#

I'm struggling to parse JSON in c# that is structured like the example below. The code snippet I have been using is somewhat functional, but it lacks stability. (I'm also looking for guidance on how to parse JSON in Javascript, which is another ...

Bootstrap 4 modal experiencing issues with the form end tag functionality

Currently, I am facing an issue while attempting to incorporate a confirmation delete feature using a Bootstrap 4 modal in my Laravel project. The problem arises when the modal is opened, and the submit button fails to function. Upon inspecting the browser ...