Search code examples
javascriptvue.jsstring-length

Vue count string length


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 ?


Solution

  • 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.