Ken Ramirez
Ken Ramirez

Reputation: 335

Retrieve data attribute value of clicked element with v-for

I've made a datalist which is filled dynamically and it works correctly.

Now, I need listen the click event on the options to retrieve the data-id value and put it as value in the input hidden.

I already tried with v-on:click.native and @click but there is no response in the console.

Any idea? I'm just starting at Vue, hope you can help me.

Edit: Looks like it doesn't even fire the function. I've tried v-on:click="console.log('Clicked')" but nothing happens.

<input type="hidden" name="id_discipline" id="id_discipline">

<input list="disciplines" id="disciplines-list">
<datalist id="disciplines">
    <option 
    v-for="discipline in disciplines" 
    :key="discipline.id_discipline"
    :data-id="discipline.id_discipline" 
    v-on:click="updateDisciplineId($event)" 
    >{{discipline.name}}</option>
</datalist>
methods: {
    updateDisciplineId(event) {
        console.log('clicked!);
    } 
},

Upvotes: 1

Views: 1783

Answers (1)

saibbyweb
saibbyweb

Reputation: 3264

Using datalist is not suited for what you want to acheive, however there's a workaround with a limitation.

Template:

<template>
  <div>
    <input
      type="text"
      name="id_discipline"
      v-model="selectedID"
      placeholder="Data id value of clicked"
    />
    <input
      @input="onChange"
      list="disciplines"
      id="disciplines-list"
      class="form-control"
      placeholder="Seleccionar disciplina"
    />
    <datalist id="disciplines">
      <option
        v-for="discipline in disciplines"
        :key="discipline.id_discipline"
        :data-value="discipline.id_discipline"
        >{{ discipline.name }}</option
      >
    </datalist>
  </div>
</template>

Script Part:

<script>
export default {
  data() {
    return {
      selectedID: "",
      id_discipline: "",
      disciplines: [
        {
          id_discipline: 1,
          name: "Yoga"
        },
        {
          id_discipline: 2,
          name: "Functional"
        }
      ]
    };
  },
  methods: {
    onChange(e) {
      this.getID(e.target.value).then(
        resposnse => (this.selectedID = resposnse)
      );
    },
    async getID(value) {
      let promise = new Promise((resolve, reject) => {
        this.disciplines.forEach(item => {
          if (item.name === value) resolve(item.id_discipline);
        });
      });

      return await promise;
    }
  }
};
</script>

Here's a working Sandbox demo.

**Limitation: Discipline name (Yoga, functional) should be unique.

Upvotes: 3

Related Questions