VueJs – Array of options with multi select checkbox and a textfield with value

Hello I’m trying to set the option value in a textfield when selected. The text input will only show when an option is selected and the value from the array user.roles should populate on input text as illustrated below but for some reason that won’t work. Not sure why value can’t simply show..

new Vue({
  el: '#app',
  data: {
    user: {
      email: 'test@test.com',
      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.includes(role)">
              
              <input type="text" value="The value from user.roles should go here.... instead of the value of role.value {{role.value}} /*** this does not work for some reason*/">
            </p>
        </div>

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

1 thought on “VueJs – Array of options with multi select checkbox and a textfield with value”

  1. It’s because you declare an empty string for the ‘value’ property in roles array,

    Edit

    new Vue({
      el: '#app',
      data: {
        user: {
          email: 'test@test.com',
          roles: [{id: 1, name:'Client', value:'this is just a value'}]
        },
        roles: [
          {
            id: 1,
            name: 'Client',
            value:'Client Role',
          },
          {
            id: 2,
            name: 'Admin',
            value:'Admin Role',
          },
          {
            id: 3,
            name: 'Guest',
            value:'Guest Role',
          }
        ]
      }
    })
    <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="index">
                <label>{{role.name}}</label>
                <input type="checkbox" v-model="user.roles" :value="role"/>
    
                <p v-if="user.roles.includes(role)">
                  <input type="text" :value="user.roles[index].value">
                </p>
            </div>
    
            <p>User's selected roels</p>
            {{user.roles}}
            </template>
    </div>
    Reply

Leave a Comment