0

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.

0

3 Answers 3

2

Hi Daniel I think you might need to change type="number" to text to allow you to use a non numeric value

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you Jev! Changed it to this and now it works: jsfiddle.net/Daniel_Knights/6xn12tj9/11
1

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();
            }
        }
  }
})

2 Comments

Tweeked your answer a bit and this works really well: jsfiddle.net/Daniel_Knights/6xn12tj9/32
It's also worth noting that keycodes are slightly different depending on which browser you're using.
0

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.