VueJS: interactive input field with dynamic value binding using v-model

I am facing an issue with VueJS regarding setting the value of an input radio along with v-model. I am confused as to why I am unable to dynamically set a value to an input and use a model to retrieve the user's selection.

Here is a clearer representation in code:

export default {
  props: ["question", "currentQuestion"],

  data() {
    return {
      answer: undefined
    }
  },
  computed: {
    isCurrent() {
      return this.currentQuestion && this.currentQuestion.id == this.question.id;
    }
  },
  methods: {
    groupName(question) {
      return 'question_id_' + question.id
    },
    inputType(question) {
      if (question.question_type_id == 2) return "checkbox";
      return "radio";
     }
  },
  mounted() {
    console.log('Component mounted.')
  }
    }
<template>
    <ul v-if="question.question_type_id != 4">
       <li v-for="option in question.options" :key="option.id">
         <div class="form-group">
           <label>
              <input v-model="answer" :value="option.id" :type="inputType(question)" 
    :name="groupName(question)" />
           {{option.option}}
           </label>
         </div>
       </li>
    </ul>
</template>

Therefore, if there are four options, the user would see four radio buttons, each with the "option.id" as a value. When the user clicks a radio button, the model "answer" should be populated with that value.

However, upon compiling the file, I encounter the following error message:

  • :value="option.id" conflicts with v-model on the same element because the latter already expands to a value binding internally

Can someone assist me in understanding how to dynamically set a value to an input and associate a model to retrieve the selected value?

Additionally, the VueJS documentation on this page outlines exactly what I am attempting to achieve: https://v2.vuejs.org/v2/guide/forms.html

https://i.sstatic.net/JmxJ7.png

Your help is greatly appreciated.

Answer №1

The primary issue at play is the utilization of a dynamic type in the input element, causing potential confusion for Vue. When combining value with v-model for a checkbox input, it is typically not valid unless binding to an array.

To address this, consider implementing a v-if/v-else statement.

<label>
  <input v-if="question.question_type_id == 2" 
         v-model="answer" 
         type="checkbox" 
         :name="groupName(question)" />
  <input v-else 
         v-model="answer" 
         :value="option.id" 
         type="radio" 
         :name="groupName(question)" />
  {{option.option}}
</label> 

Here's a functional example.

While there may be other issues present, the mentioned solution addresses the error scenario. It's important to note that having multiple checkboxes linked to a single v-model without using an array can lead to complexity. In such cases, adapting the data type of answer based on the specific context – radio, single value checkbox, or multi-value checkbox – could become convoluted.

Answer №2

To ensure proper functionality, it is recommended to utilize placeholders in your code.

<input :placeholder="option.id" v-model="answer" @input="functionToChangeValue($event)"/>

Warning: Do not combine the use of VALUE and V-MODEL together as it can create conflicting bindings and potentially disrupt your code's functionality.

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

Unable to assign a value to a variable within a Mongoose callback function

I am struggling to comprehend why the variable "productsAvailable" still shows true even after being set to false. router.post('/api/transactions', (req, res) => { var productsAvailable = true for(var i=0; i<3; i++) { Prod ...

Iterating over the local storage to locate a specific item

Utilizing local storage extensively has been beneficial for maintaining state by storing the session on the client side. However, a challenge arises when updating the session. Within my code, there are multiple lists of objects that I serialize in JSON fo ...

Issue with Plesk Obsidian, IISNode, and Express - application functioning solely in local environment

After setting up my Node.JS + Express.JS application on my server with IISNode and Plesk Obsidian, browsing the page in a browser triggers an error: I have already verified the permissions of the relevant folders and ensured that the "App Identities" have ...

A custom script developed to detect the presence of the numeric combination "11" and promptly notify the

I am attempting to develop a unique chrome extension that detects typing errors in orders. For example, if the user accidentally types "11" instead of "1", an alert should be triggered. However, I am encountering an issue where the script is running in an ...

Access to Web Share API requires permission

I am currently attempting to integrate the Web Share API feature into my testing web application, but unfortunately, I seem to be encountering some difficulties. Below is the code snippet I have been working with: const newVariable: any = navigator; {newV ...

AngularJS: Setting up filter asynchronously

I'm facing a challenge when trying to set up a filter that requires asynchronous data. The filter's purpose is simple - it needs to convert paths to names, but this task involves a mapping array that must be fetched from the server. While I cou ...

The ternary operator, also known as the conditional operator

One feature I have implemented is a button that can generate a random color and update the color state with this value. The color state is then used to define the background color of the div. Within the div, there is a lock/unlock button that toggles the ...

"Trouble With JSON and ASP.NET WebMethod: Server-Side Method Not Executing

I am attempting to send parameters to my code behind using the WebMethod. Although I am successfully reaching the end of ajax, the method in my aspx.cs code behind is not being called and I am encountering an error. Operation failed! Details: '[ob ...

Need help tackling this issue: getting the error message "Route.post() is asking for a callback function, but received [object Undefined]

I am currently working on implementing a new contactUs page in my project that includes a form to store data in a mongoDB collection. However, after setting up all the controller and route files and launching the app, I encountered an error that I'm u ...

jPlayer calculates the "duration" as 1,440 minutes on iOs devices for all mp3 files

My homemade webpage is designed for playing mp3s and viewing pdfs. I'm using jPlayer v 2.9.2 to play the mp3s, which works fine on PC but encounters issues on iPhone. The duration values are incorrect, showing "1439:59" remaining for all files, causin ...

What's the better approach for creating Maps and Sets in ES6: relying on a compiler or leveraging syntactic sugar?

It has always baffled me why we are unable to write ES6 Maps in the following way: new Map({ ['ArrayAsKey']: {foo:bar} }) Is there a workaround for this limitation? Or perhaps a technique that enhances the experience of utilizing these mode ...

JavaScript regular expressions: filtering out results from the output

I'm trying to extract a specific number from a dynamically added string. The text looks like this: nisi non text600 elit, where 600 is the number I need to retrieve. Is there a way to achieve this without replacing the word text? var str = ('nis ...

Tips for finding the index of data in Cesium

After successfully completing the tutorial on building a flight tracker, I am facing a challenge. I want to access the current index of my data at any given time while my app is running cesium and displaying the airplane animation following the flight path ...

create a nested promise with a delay in a node.js environment

Utilizing Google geocoding in my coding tasks has presented a challenge. I have around 50 places to geocode, but Google restricts the number of places that can be geocoded simultaneously, resulting in an 'OVER_QUERY_LIMIT' error. To address this ...

Access the contents of the selected cell in the MUI datagrid

When I choose a row from the datagrid, my attempt to access each cell value in that row always returns "undefined" when using selectedRowData.email. How can I correctly retrieve the data from a selected row's cells? <DataGrid checkboxSe ...

Is it necessary to utilize Babel with Node.js?

I am aware that Node.js fully supports ES6 now, using version 7.2.1. Recently, I was advised by someone that the current ES6 implementation in Node.js may not be production ready and that I might need to use Babel for a more robust ES6 set-up. After visit ...

Creating a WebSocket service similar to stackoverflow using Node.js: A step-by-step guide

I'm currently developing a chat application using node.js. I have implemented a feature to receive new messages via ajax, where requests are sent every 3 seconds. However, I recently observed that stackoverflow handles fetching new data differently. I ...

The compatibility between JSON and the CORS header 'Access-Control-Allow-Origin' is crucial

I am trying to obtain the value from a JSON file that is located on the server. To retrieve this value, I am using AJAX. However, when checking the console for errors, I receive the following message: Cross-Origin Request Blocked: The Same Origin Poli ...

The MongoDB oplog displays repetitive patterns at unpredictable intervals

My current focus is on utilizing MongoDB and the oplog has proven to be a crucial component of my application. However, I've noticed a recurring issue during development where the oplog contains duplicate records (changes) 3 or 4 times. In an attempt ...

Tips for creating an auto-incrementing ID within Firebase's real-time database

How can I create an automatic incrementing ID for entries in a Firebase database? The first item should have an ID of 1, and the second one should be 2. var database = firebase.database(); var userDetails = database.ref("Article"); userDetails. ...