Vue count string length

Viewed 3748

VIEW

<div v-for="(listings, index) in list4" :key="index">
   <input v-model="listings.rfidState2" type="text"/>
</div>

<div v-for="(element2, index) in list4" :key="index">
  <p v-if="list4[index].rfidState2 > 0">WORKING</p>
</div>

If I insert value as AC87SG67A for an input field it throws me an error at v-if="list4[index].rfidState2 > 0" but if I insert the value as 98292001 it displays WORKING. Is there a way to display WORKING for any value inserted such as integer or alphabet(a to z) inside <input v-model="listings.rfidState2" type="text"/> textfield ?

2 Answers

First, you can add a .trim modifier to the input like:

<input v-model.trim="listings.rfidState2" type="text"/>

Now, any whitespace from user input to be trimmed automatically. Next, we can simply check if any text was entered or not like:

<p v-if="list4[index].rfidState2.length">WORKING</p>

So, if any integer or alphabet is entered then length will return a value greater than 0, which is truthy and thus the v-if will show the element, else it will be hidden.

list4[index].rfidState2 is a string. You cannot compare it with a number. If you do so, JavaScript will do the implicit type conversion, and the result will not make sense. list4[index].rfidState2.length is the actual length of the string. So, what you should write is "list4[index].rfidState2.length > 0"

Related