jkstallard
jkstallard

Reputation: 395

How do I pass a data attribute in vue js select option

I need to pass a select object data attribute to a function on change. I can pass the value fine, but how can I pass the test attribute below? e.target.test returns undefined.

<select v-model="prog.programme_id" @change="updateTest">
    <option v-for="programme in programmes" :key="programme.id" :value="programme.programme_id" :test="programme.newval">{{ programme.title }} )</option>
</select>

method:

updateTest(e){
     console.log(e.target.value)
},

Upvotes: 2

Views: 3336

Answers (1)

Mr.P
Mr.P

Reputation: 1257

event.target refers to the SELECT not the options... you have to select the selected option and get it's attribute

event.target.options[event.target.options.selectedIndex].getAttribute('test')

here is the full component example

<template>
  <div>
    <select v-model="val" @change="updateTest($event)" style="width: 100px" test="Test">
        <option v-for="programme in list" :key="programme.id" :value="programme.id" :test="programme.name">{{ programme.value }} )</option>
    </select>
  </div>
</template>

<script>
export default {
  name: 'HelloWorld',
  data() {
    return {
      val: null,
      list: [
        {id: 1, name: "John", value: "A"},
        {id: 2, name: "Jack", value: "B"},
      ]
    }
  },
  methods: {
    updateTest(event) {
      console.log(event.target.options[event.target.options.selectedIndex].getAttribute('test'))
    }
  }
}
</script>

<style scoped>
</style>

Upvotes: 4

Related Questions