nsukhi singh
nsukhi singh

Reputation: 39

How to get the ID from a table inside a b-modal and display on the page in VUEJS

I am facing issue where i want to get the ID from the table when clicking on the button inside a modal and display it on the main page.

Here is the HTML code

<template>
  <div class="hello">
    <p>Selected id :</p>
    <b-button class="mt-2" variant="primary" v-b-modal.modal-xl>
      Select codes
    </b-button>
    <b-modal id="modal-xl" size="lg" centered hide-footer="true">
      <table class="table sortable" data-page-list="[10, 25, 50, 100, all]">
        <thead>
          <tr>
            <th>ID</th>
            <th>Code</th>
            <th>Button</th>
          </tr>
        </thead>

        <tbody>
          <tr>
            <td>1</td>
            <td>2222</td>
            <td>
              <b-button variant="primary">Select</b-button>
            </td>
          </tr>
          <tr>
            <td>2</td>
            <td>33333</td>
            <td>
              <b-button variant="primary">Select</b-button>
            </td>
          </tr>
          <tr>
            <td>3</td>
            <td>4444</td>
            <td>
              <b-button variant="primary">Select</b-button>
            </td>
          </tr>
        </tbody>
      </table>
    </b-modal>
  </div>
</template>

Here is the Codesandbox for it.

Any help much appreciated.

Upvotes: 0

Views: 472

Answers (1)

Liel Fridman
Liel Fridman

Reputation: 1198

One way to do that is to save the selected ID as the local state. In addition, I'd recommend using v-for and an array to store the codes list, and then you can pass the id to the event:

<template>
  <div class="hello">
    <p>Selected id: {{ selected }}</p>
    <b-button class="mt-2" variant="primary" v-b-modal.modal-xl>
      Select codes
    </b-button>
    <b-modal id="modal-xl" size="lg" centered hide-footer="true">
      <table class="table sortable" data-page-list="[10, 25, 50, 100, all]">
        <thead>
          <tr>
            <th>ID</th>
            <th>Code</th>
            <th>Button</th>
          </tr>
        </thead>

        <tbody>
          <tr v-for="code in codes" :key="code.id">
            <td>{{ code.id }}</td>
            <td>{{ code.code }}</td>
            <td>
              <b-button variant="primary" @click="onSelected(code.id)">Select</b-button>
            </td>
          </tr>
        </tbody>
      </table>
    </b-modal>
  </div>
</template>

<script>
export default {
  name: "HelloWorld",
  props: {
    msg: String,
  },
  data() {
    return {
      codes: [
        {id: 1, code: 2222},
        {id: 2, code: 3333},
        {id: 3, code: 4444},
      ],
      selected: null
    }
  },
  methods: {
    onSelected: function(id) {
      this.selected = id;
    }
  }
};
</script>

You can check out a working example here.

Upvotes: 1

Related Questions