Reputation: 8368
I have an input where users can enter a price. When the user presses a number key, I want to prepend whatever they type with a '£' sign.
Like this but visible in the input field, not just bound to a data property:
// empty
£1 // first keydown
£12
£125
Example: https://jsfiddle.net/Daniel_Knights/6xn12tj9/6/
Any ideas how to achieve this? Tried a few things but I'm stumped.
Upvotes: 0
Views: 2393
Reputation: 3988
This is because you set your input type to number. so you can only use number.
But if you want to force user to enter only number, you can do this:
<div id="app">
<input type="text" :placeholder="placeholderPrice" v-model="price" @keypress="mustNumber"/>
<div class="price">
<p v-if="price !== ''">
</p>
{{ price }}
</div>
</div>
new Vue({
el: "#app",
data: {
price: "£",
},
methods: {
inputPrice(e) {
this.price = `£${e.target.value}`;
},
mustNumber($event) {
let keyCode = $event.keyCode ? $event.keyCode : $keyCode;
// only allow number and one dot
if (
(keyCode < 48 || keyCode > 57) &&
(keyCode !== 46)
) {
$event.preventDefault();
}
}
}
})
Upvotes: 1
Reputation: 1
You need masked input. For example you can use https://vuejs-tips.github.io/v-money/ library
<template>
<div>
<money v-model="price" v-bind="money"></money> {{price}}
</div>
</template>
<script>
import {Money} from 'v-money'
export default {
components: {Money},
data () {
return {
price: 123.45,
money: {
decimal: ',',
thousands: '.',
prefix: '£ ',
suffix: '',
precision: 2,
masked: false
}
}
}
}
</script>
Upvotes: 0
Reputation: 129
Hi Daniel I think you might need to change type="number" to text to allow you to use a non numeric value
Upvotes: 2