0

I'm bringing in an array (contacts) and iterating over it in the option tag which I'm showing as selected if the array contact id is equal to the selected_contact. This works fine but I then want to bind the newly selected option to the data to add a new activity but it doesn't work. What am I doing wrong?

<select v-model="selected" class="border py-2 px-3 text-grey-800 w-full" name="contact_id">
                   

  <option v-for="contact in contacts" v-bind:selected="contact.id === selected_contact">{{contact.name}}
  </option>

</select>

here is what I have in the data()

data() {
            return {
                name: '',
                selected: '',
                activity_type_id: '',
                comments: ''
            }
        },

Then I'm trying to send it with this onclick :

<div class="px-8 py-4 border-gray-200 flex items-center">
          <button @click="addActivity" class="bg-teal-300 hover:bg-teal-800 text-white font-bold py-2 px-4 rounded ml-4 mt-3 mr-15">Add Activity</button>
   
        </div>

Using the addActivity function below:


 addActivity(){

                    let activityAdd = {
                           comments: this.comments,
                           contact_id: this.selected,
                           activity_type_id: this.activity_type_id,
                        }
                        console.log(activityAdd);
                        this.$inertia.post('/activity', activityAdd)
                    },
James Roe
  • 11
  • 2

1 Answers1

0

BY BINDING VALUE

<template>
  <div>
    <select v-model="selected" class="border py-2 px-3 text-grey-800 w-full" name="contact_id">
      <option
        v-for="contact in contacts"
        :key="contact.id"
        :value="contact.id"
      >{{contact.name}}</option>
    </select>
  </div>
</template>

USING COMPUTED PROPERTIES

<template>
  <div>
    <select v-model="selected" class="border py-2 px-3 text-grey-800 w-full" name="contact_id">
      <option v-for="contact in contacts" :key="contact.id">{{contact.name}}</option>
    </select>
  </div>
</template>

Selected is an object so you can initialize it like it:

 data() {
    return {
      name: "",
      selected: {},
      activity_type_id: "",
      comments: "",
    };
  },

You can use a computed property to get the id:

 computed: {
    selectedID: function () {
      return this.selected.id;
    },
  }

And the method becomes:

  methods: {
    addActivity() {
      let activityAdd = {
        comments: this.comments,
        contact_id: this.selectedID,
        activity_type_id: this.activity_type_id,
      };
      this.$inertia.post("/activity", activityAdd);
    },
  },
catmal
  • 1,728
  • 1
  • 16
  • 32