Skip to content
Advertisement

How to extract an id from id field in html to send it via axios in Vue?

I’ve no idea how to get the id of element in order to send it. I use Vue 2.

** offers array i get from the API, so it is just an example.

I need getting id dynamically in order to send a comment for the exact offer.

Maybe it is the wrong way to do it, but it would be great if it worked this way

HTML:

<div v-for="offer in offers">
        <p> {{ offer.description }}</p>

      <div class="form-group col-md-9">
        <b-form-textarea :id="`${offer.id}`" placeholder="Comment!" rows="1" v-model="text"></b-form-textarea>
        <button @click="createComment()" class="button btn btn-success">Send!</button>
      </div>

</div>

JS:

data () {
      return {
          offers: [
    {id: 1,
     description: "some"
    },
    {id: 2,
     description: "another"
    },
],
        }
    },


        methods: { 
  createComment() {
     const FormData = { 
      text: this.text,
      offer_related:   NEED TO GET THE VALUE OF TEXTAREA :id here
    } 
    // axios
    // .post(`/api/v1/comments/`, FormData)
  },


Advertisement

Answer

Great thanks to @don_aman!

The final code will look like:

<div v-for="offer in offers">
        <p> {{ offer.description }}</p>

      <div class="form-group col-md-9">
        <b-form-textarea :id="`${offer.id}`" placeholder="Comment!" rows="1" v-model="text[offer.id]"></b-form-textarea>
        <button @click="createComment(`${offer.id}`)" class="button btn btn-success">Send!</button>
      </div>

</div>

JS:

data () {
      return {
          offers: [
    {id: 1,
     description: "some"
    },
    {id: 2,
     description: "another"
    },
],
     text: {},
        }
    },


        methods: { 
  createComment(id) {
     const FormData = { 
      text: this.text[id],
      offer_related:id,
    } 
    axios
    .post(`/api/v1/comments/`, FormData)
  },
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement