skip to Main Content

i have a project using Vue js and Quasar.

I have an input field that is initialized with 10 zeros that only allows numeric numbers.
If I want to add a number, it should fill it in from behind.

"0000000000" -> fill in 1

"0000000001" -> fill in 2

"0000000012" -> fill in 5

"0000000125" -> delete last character

"0000000012" -> fill in 3

"0000000123"

any ideas how i can achieve this? This is what i have currently:

<template>
<div> 
<q-input class="input" v-model="number" outlined label="number"  mask="##########" minLength="10" maxlength="10" @input="onInput"/>
</div>
</template>

<script>
import { ref } from 'vue'

export default {

setup() {
const number = ref("0000000000")

}
return {
number
}
}
</script>

onInput does nothing so far

2

Answers


  1. You should use

    mask="#########" fill-mask="0" reverse-fill-mask
    

    But it only works well with maxlength="x" and mask="#*(x-1) ( mask="#########") and does not work with mask="#*x

    const { createApp, ref } = Vue;
    
    const app = createApp({
      setup () {  
        const number1 = ref(0)
        const number2 = ref('0000000000')
        const onInput = (newVal) => {
          number2.value = ('000000000'+ newVal).slice(-10);
        }
        return { number1, number2, onInput }
      }
    })
    
    app.use(Quasar)
    app.mount('#q-app')
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/quasar.prod.css" rel="stylesheet" type="text/css">
    <div id="q-app">
    Standard mask: <br/>
    number1: {{number1}}
    <q-input class="input" v-model="number1" outlined label="number" mask="##########" fill-mask="0" reverse-fill-mask minLength="10" maxlength="10" @update:model-value="onInput"></q-input><br/>
    Custom mask: <br/>
    number2: {{number2}}<br/>
    <q-input class="input" v-model="number2" outlined label="number" minLength="10"  @update:model-value="onInput"></q-input>
    </div>
    <script src="https://cdn.jsdelivr.net/npm/vue@3/dist/vue.global.prod.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/quasar.umd.prod.js"></script>
    Login or Signup to reply.
  2. You can use the function String.prototype.padStart to add leading 0 characters until a certain string lenght.

    Just update the v-model accordingly whenever it changes.

    <script setup>
    import { ref, watch } from 'vue'
    
    const counter = ref('')
    watch(counter, () => {
      // remove leading 0
      counter.value = counter.value.substring(Array.from(counter.value).findIndex(v => v !== '0'))
      // add leading 0 if necessary
      counter.value = counter.value.padStart(8, '0')
    })
    
    </script>
    
    <template>
      <input v-model="counter" placeholder="Enter a number">
    </template>
    

    Here is the live demo

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search