Home > Blockchain >  Convert string to boolean for checkbox
Convert string to boolean for checkbox

Time:10-30

I use v-model to display checked/unchecked checkboxes:

<template v-for="(item, index) in myFields">
  <v-checkbox
     v-model="myArray[item.code]"
     :label="item.name"       
   />
</template>

It works fine when I get true or false values from API. But now I get strings: "true" or "false" and my checkbox is always checked. If I change the code on:

v-model="Boolean(myArray[item.code])"

I got the error:

'v-model' directives require the attribute value which is valid as LHS

How can I solve this problem?

CodePudding user response:

Trying Boolean(myArray[item.code]) won’t work anyway because the string 'false' is true. So Boolean('false') return true.

Instead you should do myArray[item.code] !== 'false'
'false' will return false and every other string than false will return true

EDIT: You need to change myArray to an array of boolean like so

myArray.map((element) => element !== 'false')

Then this code will work

<template v-for="(item, index) in myFields">
  <v-checkbox
     v-model="myArray[item.code]"
     :label="item.name"       
   />
</template>
  • Related