Guide on incorporating text into user input using Vue.js

Users have the option to input a price, but I want to enhance this by automatically adding a '£' sign whenever they type a number key.

This is how it should look in the input field:

// empty
£1 // first keydown
£12
£125

For reference here's an example: https://jsfiddle.net/Daniel_Knights/6xn12tj9/6/

Any suggestions on how to make this happen? I've tried a few things without much success.

Answer №1

Hello Daniel, I suggest switching the input type from "number" to "text" in order to accept non-numeric values.

Answer №2

If you've set your input type to number, it means that only numbers can be entered.

However, if you want to strictly enforce that users enter only numbers, you can achieve this by:

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

Answer №3

To implement masked input, consider using the library in your project.

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Exploring Data Objects in Vue.js

I have a data() object in my Maincomponent.vue. Inside the data(), there is an array named myDatabase that contains multiple objects. My goal is to utilize methods to access the fields within myDatabase. I am looking to create functionality to toggle the ...

Exploring the process of traversing a function for each ng-repeat element

Hey everyone, I'm currently facing an issue where I need to pass each date through a function in order to get the desired result. Let's take a closer look at the code snippet: <md-list> <md-divider ></md-divider> ...

Simply drag and drop the image from your browser window into the file input

Is there a way to drag an image from a browser window into a file input that I developed? Looking for assistance in creating an event that allows me to get the image when dragging it to an input. While I have successfully created an event to obtain the i ...

Passing props from Vue3 to a component being rendered through RouterView

I'm facing an issue with the following code snippet: <template> <router-view /> </template> <script setup lang="ts"> ... const product: Ref<IProduct|undefined>: ref(); ... </script> The challenge is ...

Achieving unique proportions with HTML5 video resizing

On my page, I plan to showcase a video specifically for desktop browsers. I have devised some code to determine whether the video is in landscape or portrait orientation. The challenge lies in deciding what to do based on this orientation: If the video is ...

What steps can I take to stop the browser from refreshing a POST route in Express?

Currently, I am using node along with stripe integration for managing payments. My application includes a /charge route that collects various parameters from the front end and generates a receipt. I am faced with a challenge on how to redirect from a POST ...

Retrieving JSON Data from an API with JavaScript/jQuery

Having some trouble with JSON parsing using jQuery and JavaScript. I'm trying to fetch weather information from the open weather simplest API, but for some reason it's not working. When I hardcode the JSON data into a file or my script, everythin ...

Creating a validation error in Angular: When a user submits an empty form, radio buttons will be highlighted in red

I have encountered an issue already posted on GitHub regarding this matter, but unfortunately, no solution has been provided yet. You can view the issue here: https://github.com/angular/components/issues/11333 I was wondering if there are any workarounds ...

concentrate on the input box

Once I click on the CPM, my goal is to automatically place the cursor in the centralized field of this page: . Despite my attempts to use different code snippets in the console, I have not been successful. I experimented with document.getElementById("se ...

Ways to personalize the interface following the selection of an item from a dropdown menu

Currently, I am using Vue.js and Typescript for my project work. I have a requirement to customize the interface by making adjustments based on the selected item from a drop-down list. <b-form-select id="input-topic" ...

NodeJS cronjob failing to trigger Mongoose query callback

I am currently constructing a REST API backend using NodeJS and testing it locally. As part of this process, I am setting up a cron job to clear expired 'login token reset codes' from the database. These codes are created temporarily for password ...

Run the function once the page has completed downloading and bootstrapping

After experimenting with $evalAsync and $viewContentLoaded, I've found that they only trigger after Angular has completed populating the template. My goal is to determine, from within a directive: Is the template fully replaced by Angular? Have all ...

How to properly escape JSON with hyphen or dash in AngularJS ngSrc

Having trouble displaying an image from a json url with dashes. I attempted to use bracket notation but it does not seem to be functioning: <img ng-src="{{image.['small-size'].url || image.thumb}}"> When using single quotes, my angular vi ...

Tips for unchecking a checkbox when another checkbox is checked in Angular

My table displays a list of deleted items. Users have the option to either recover the item or delete it permanently. I am seeking assistance in ensuring that only one checkbox is checked in a table row, and unchecking other checkboxes if the user tries t ...

Configuring properties of a child component in VueJS

Currently, I'm exploring the method of utilizing a Vue template as a Kendo UI template in their components. However, I found that there's a lack of clarity on how to provide properties to components rendered using this approach instead of directl ...

In order to have JavaScript showcase a random word from a list when a button is clicked and then display it in a heading 3, follow these steps:

How can I create a JavaScript function that displays a random word from a list when a button is clicked and prints it in a heading 3? I would appreciate a quick response. //Start of Js code let display = document.getElementById("motivato"); console.log(di ...

Having trouble with setting up ENV variables while deploying the app on Heroku

I recently deployed my node.js app to Heroku, and I'm facing some issues with its functionality. The app loads fine, but when I try to sign in, it breaks down. It seems like the environment variables are not loading correctly, specifically the db vari ...

The Typescript error message states: "Unable to access 'add' property of null"

I am trying to implement a role command in discord.js v13.6, but I am facing an issue where it cannot read the line related to adding a role. The error message displayed is Typescript: Cannot read properties of null (reading "add"). How can I resolve thi ...

How can I use a JavaScript function to remove an element from a PHP array?

Imagine I have a PHP session array: $_SESSION[MyItems]=Array('A'=>"Apple", 'B'=>"Brownie", 'C'="Coin")) which is utilized to showcase items on a user's visited page. I want the user to have the ability to remove o ...

Shine a spotlight on elements that match with jQuery using live() or on()

Check out my jsFiddle demonstration where I have created a button that adds elements and provides links to delete these elements. Instead of actually deleting the elements in this example, I want to make it so that hovering over the (remove) link, which is ...