Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

craigwillis85's avatar

binding checkbox values if present in another array

Hi

I have an API that returns some data.

The data that is returned, is an array of objects (countries - quite a few of them). Also I'm returning the countries associated with the object I'm concerned about

For example

When User A is loaded, my API returns all the countries and the countries associated with User A.

What I want to do therefore, is display all of the countries as checkboxes and then have the ones that User A has as pre-selected.

countries - is an array of objects with an id and name
user -  is an object that contains an array of country objects (with an id and name as above)

I currently have:

<ul class="country-columns">
    <li class="control" v-for="country in countries">
        <label class="checkbox">
          <input type="checkbox" v-model="country.id" v-bind:value="permission.id">
          <span>{{ country.name }}</span>
       </label>
    </li>
</ul>

But this doesn't take into account the user.countries to select the ones in that array.

Is there an easy way to check if the users countries is in the countries array and check the relevant checkbox?

Thanks

0 likes
2 replies
jstoone's avatar

Possible solution

With Vue you can conditionally set an attribute like the following:

<ul class="country-columns">
    <li class="control" v-for="country in countries">
        <label class="checkbox">
          <input type="checkbox" v-model="country.id" v-bind:value="permission.id" v-bind:checked="user.countries.includes(country.id)">
          <span>{{ country.name }}</span>
       </label>
    </li>
</ul>

From the docs:

Mustaches cannot be used inside HTML attributes, instead use a v-bind directive:

<div v-bind:id="dynamicId"></div>

It also works for boolean attributes - the attribute will be removed if the condition evaluates to a falsy value:

<button v-bind:disabled="someDynamicCondition">Button</button>

I hope this helps

Please or to participate in this conversation.