Toby Fieldgroove
Toby Fieldgroove

Reputation: 625

vuejs How to retrieve the value from elements generated in loop

So, I'm generating a table containing a checkbox and a textfield from an array of items, like a "questionnaire" where the questions come from a database.

Now, how do I, in good vue manner, retrieve if the checkboxes are checked and any text potentially input to the textfields?

I noticed that by putting "ref" on the textfields/checkboxes they become an array of vue components that are iteratable in javascript. But I haven't yet figured out how to retrieve the values correctly.

I mean, there's always the good old "get element by id" in javascript but it feels like there should be a fancier way..more "vue"-ish...

<table ref="questionnaire">
        <tr
          :id="item.questionId"
          row
          wrap
          v-for="(item, index) in questions"
          :key="item.questionId"
          :ref="'row_' + item.questionId"
        >
          <td>
            <label>{{item.name}}</label>
          </td>
          <td>    
            <v-checkbox ref="cbQ" value="value"></v-checkbox>
          </td>
          <td>
            <v-text-field label="Answer" ref="tbQ"></v-text-field>
          </td>
        </tr>
      </table>

Upvotes: 0

Views: 582

Answers (1)

Davide Castellini
Davide Castellini

Reputation: 519

You could "prepare" server side your array of questions for accepting a checked value and a text answer and then bind every checkbox and text-field to their questions with v-model like:

<table ref="questionnaire">
    <tr
          :id="item.questionId"
          row
          wrap
          v-for="(item, index) in questions"
          :key="item.questionId"
          :ref="'row_' + item.questionId"
    >
        <td>
            <label>{{item.name}}</label>
        </td>
        <td>    
            <v-checkbox ref="cbQ" v-model="item.checked"></v-checkbox>
        </td>
        <td>
            <v-text-field label="Answer" ref="tbQ" v-model="item.answer"></v-text-field>
        </td>
    </tr>
</table>

But before that you should map checked and answer attributes on your questions so the v-model has already the said attributes to bind on.

At the end you will end up with an array of questions with the answers binded inside each of them.

Upvotes: 1

Related Questions