VueJs - Checkbox and Textfield linked to v-model and value determined by chosen option

Hey there! I am currently facing an issue with setting a value when one of the options is selected. The text input is supposed to appear only when an option is selected, and the value from the array user.roles should populate the input text field. However, I can't seem to figure out why it's not working as intended. Any assistance on this matter would be highly appreciated.

new Vue({
  el: '#app',
    data: {
      user: {
        email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b8ccddcbccf8ccddcbcc96dbd7d5">[email protected]</a>',
        roles: [{id: 1, name:'Client', value:'this is just a value'}]
      },
      roles: [
        {
          id: 1,
          name: 'Client',
          value:'',
        },
        {
          id: 2,
          name: 'Admin',
          value:'',
        },
        {
          id: 3,
          name: 'Guest',
          value:'',
        }
      ]
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
<template>
  
  <label>Email</label>
  <input type="text" v-model="user.email" />
       
   </div>
   <div v-for="(role,index) in roles" :key="role.id">
     <label>{{role.name}}</label>
       <input type="checkbox" v-model="user.roles" :value="role"/>

       <p v-if="user.roles.filter(e => e.id === role.id).length > 0">
         <input type="text" value="The value from user.roles should go here.... instead of the value of role.value">
       </p>
        
    </div>

    <p>User's selected roles</p>
    {{user.roles}}
    
    </template>
</div>

Answer №1

Using my Vue 2 CLI 'sandbox' app for testing, I decided to create a single file component based on a provided template and Vue instance from a specific question. While it may not directly solve the issue at hand, I did encounter a problem concerning the initial checking of role checkboxes that are already assigned to a user.

In the given scenario, the user was assigned role 1, yet the corresponding checkbox failed to render as checked in my testing environment. Upon consulting the documentation regarding binding multiple checkboxes to an array (similar to the code provided), there was no mention of how to properly initialize checkboxes tied to said array.

After much futile searching, I observed a discrepancy between the 'Client' role object within the initial 'user.roles' array and the same object in the 'roles' data due to mismatched 'role.value' properties. By adjusting the pre-assigned 'value' property of the 'Client' object within 'user.roles' to an empty string, the checkbox representing 'Client' began rendering correctly upon initialization.

data() {
  return {
    user: {
      email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="661203151226120315124805090b">[email protected]</a>',
      roles: [{ id: 1, name: 'Client', value: '' }]
    },
    roles: [
      {
        id: 1,
        name: 'Client',
        value: '',
      },
      {
        id: 2,
        name: 'Admin',
        value: '',
      },
      {
        id: 3,
        name: 'Guest',
        value: '',
      }
    ]
  }
},

Answer №2

new Vue({
  el: '#app',
  data: {
    rolename: [],
    user: {
      email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="245041575064504157500a474b49">[email protected]</a>',
      roles: [{id: 1, name:'Client', value:'this is just a value'}]
    },
    roles: [
      {
        id: 1,
        name: 'Client',
        value:'',
      },
      {
        id: 2,
        name: 'Admin',
        value:'',
      },
      {
        id: 3,
        name: 'Guest',
        value:'',
      }
    ]
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
<template>

<div>
  <label>Email</label>
  <input type="text" v-model="user.email" />
</div>

<div v-for="role in roles" :key="role.id">
  <label>{{ role.name }}</label>
  <input type="checkbox" v-model="rolename" :value="role.name" />
</div>

<p>
  <input type="input" v-model="rolename" />
</p>

<p>User's selected roels</p>
{{ user.roles }}
        </template>
</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

Separate the data into categories and create pie charts to represent each one

I am currently retrieving data from a backend database server, and the information being returned is as follows: [{ "Year": 2014, "Name": "A", "Values": 18 },{ "Year": 2014, "Name": "B", "Values": 16 },{ "Year": 2015, "Name": "D", "Values": 20},{ "Year": ...

Conceal the content inside a DIV based on the character length of a

I'm having trouble trying to hide content in a div based on the length of a textbox value when a key is pressed. The current solution isn't working as expected. Is the backspace key not considered a keypress event? If you take a look at the code ...

JavaScript function that fetches data from local storage and displays it in an HTML table

I've been exploring how to incorporate a bootstrap datatable into my project. Rather than using pre-set data, I want to allow users to input their own data through a form and store it in localStorage. Understanding that I need to stringify and parse ...

Mist Conceals Celestial View (THREE.JS R76)

I have a cylindrical camera setup with fog to hide the end of the tube. However, I am trying to make the skybox visible through the alpha map sides of the cylinder. The current issue is that the fog is blocking the visibility and I'm looking for a sol ...

I'm curious about this specific expression in express.js - can you explain its significance?

Could you please provide a thorough explanation of the following line of code in NodeJS: var app = module.exports = express.createServer(); ...

Navigate between pictures using hover in jQuery

I am working on creating a feature where images cycle through individually every 2 seconds, but switch to the right image when its associated link is hovered. So far, I have managed to make the images show up on hover, but I am struggling with getting them ...

"Receiving EOF error while attempting to send JSON data to local Go backend with VueJS

I'm currently in the process of establishing a login system with VueJS for the frontend and Go for the backend. However, I've hit a roadblock when it comes to sending the username and password in JSON format to the backend. My current approach i ...

Determine if a file input is linked in React.js Material UI

Currently, I am working with a Material UI <TextField /> component that has a type=file prop to allow file attachments. My goal is to trigger an event when a file is attached to this TextField. However, my search results only provided JQuery soluti ...

Store user input in a paragraph

I want to create a unique program that allows users to input text in a field, and when they click "Start", the text will appear in a paragraph backwards. I plan to use Html, jQuery, and CSS for this project. Can anyone provide guidance on how to achieve th ...

Dynamically generating Vue components

I have a component that displays all articles, and I want to add a 'Read more' button to each article so that users can open the full content by clicking on it. The article page should pull full information from an API and have its own route path ...

Tips for re-formatting JSON data using Lodash / JavaScript

Can anyone help me with reformatting the JSON data below? [ { "name": "Hello", "value": 1 }, { "name": "Hello", "value": 11 }, { "name": "Bye", "value": 2 }, { "name": "Bye", "value": 22 } ] I want to trans ...

Prevent text from wrapping when using jQuery to animate font size

I have a unique way of showcasing content in a preview format by utilizing em units for scaling and adjusting the root font size to increase or decrease. When users click on the preview, the full content is revealed with an animation that scales the font s ...

JavaScript error type mismatch

Currently, I am utilizing select2.js to highlight a specific li element that is received as a response. var cityCounter = -1; var sul = $('.select2-search-choice'); $(".select2-input").keyup(function (e) { // TODO CODE // console.log($( ...

Passing data between functions in a JavaScript file

I need some guidance on implementing an angularjs google column chart. Specifically, I have a requirement to transfer the value from one JavaScript function to another variable defined in a separate JavaScript function. Here is an example snippet of code ...

Top method for retrieving CSS variable in a customized Angular directive

I have a question regarding the process of converting the statement below to Angular's renderer2: this.elementRef.nativeElement.style.setProperty( '--primary-color ' , '#455363' ) The above statement modifies a CSS variable in the ...

The timing of jQuery's .load function appears to be off, catching us by surprise

My current challenge involves loading returned html from an .aspx page through AJAX, but facing a timing issue with a click event that needs to occur before executing some essential tasks. Specifically, the process begins when a user types in a text field ...

What could be causing the JavaScript/jquery code in my Functions.php file to only function properly on the initial post that loads on my WordPress website?

Currently, I am in the process of developing a WordPress website where the content is refreshed weekly. This means that all posts, media, and files are removed from the WP environment every week and replaced with new content. One of the key components of ...

Ways to verify if the output from translate.instant has been properly translated at least once

With ngx-translate, I have implemented the following function and my goal is interface IWidgetFilterValue = { label: string; value: string; } getSortedOptions(filterOptionsArr: IWidgetFilterValue[]): IWidgetFilterValue[] { const filterOptionsArrNew = ...

Storing JWT API tokens in a secure location

Currently, I am in the process of developing the API portion for an application and focusing on implementing JWT authentication. At this point, I am generating a token and sending it back to the front-end as part of a JSON object when a user is created. Ho ...

Transmitting information via Ajax, jquery, Node.js, and Express

Seeking assistance as I struggle to comprehend the process while trying to implement it based on various online resources. My carousel directs users right after signing up, and I aim to gather information about their profile through simple input questions. ...