Is there a way to deactivate all dot inputs on number type input in vue.js 2?

Here is an example of my HTML code:

<div id="app">
  <input type="number" v-model="quantity"/>
</div>

This is how my Vue component looks:

new Vue({
  el: '#app',
  data: {
    quantity: ''
  },
  watch: {
    quantity (val) {
      this.quantity = val.replace('.', '')
    }
  }
})

You can check out the demo and full code here: https://jsfiddle.net/50wL7mdz/67375/

For instance, when I input 10.2, it will automatically become 102

However, if I input 10..2, it won't convert to 102

Therefore, multiple dots will not trigger the automatic conversion

Do you know how I can resolve this issue?

Answer №1

When you specify type="number", the browser undergoes some internal processing, causing the value of the input (which is linked to your variable) to be a Number, not exactly matching the text in the box.

If the text in the box is not a valid number, the internal value will be empty. Typing one '.' won't change the value: 10. and 10 hold the same numerical value. However, typing a second '.' renders the value invalid, resulting in an empty internal value. Interestingly, what you entered in the input remains visible, but retrieving it is not possible.

Your choices are to discontinue using type="number", allowing your code to function as intended (at the cost of losing the up-and-down arrow functionality for value changes), or implementing a more complex workaround.

Update: The provided solution works reasonably well by enforcing a standardized version of the number for usage. One drawback is that the cursor will jump to the end of the number after each modification. While this can be addressed, the process is fairly intricate, so it's omitted here.

new Vue({
  el: '#app',
  data: {
    quantity: ''
  },
  computed: {
    ppQuantity: {
      get() {
        return this.quantity;
      },
      set(val) {
        this.quantity = '';
        this.$nextTick(() => {
          this.quantity = val.replace('.', '');
        });
      }
    }
  }
})
<script src="https://unpkg.com/vue"></script>

<div id="app">
  <input type="number" v-model="ppQuantity">
</div>

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

Steps for embedding JavaScript code within HTML tags using a JavaScript file

Working on a React web app, I am solely using js and css files without any html. In one of my js files, there is a mix of html and js code like this: class Teams extends Component { state = { teams: [] } componentDidMount() { ...

What is the most effective way to retrieve cursors from individual entities in a Google Cloud Datastore query?

I am currently working on integrating Google Cloud Datastore into my NodeJS application. One issue I have encountered is that when making a query, only the end cursor is returned by default, rather than the cursor for each entity in the response. For insta ...

Trouble arises when attempting to parse multiple objects from a JSON file using JavaScript

Encountering JSON parsing issues with multiple JSON objects. JSON data is essential for JavaScript functionality. { "name": "Sara", "age": 23, "gender": "Female", "department": & ...

Is there a way to apply -webkit-line-clamp to this JavaScript content using CSS?

i have a random-posts script for my blogger website <div class="noop-random-posts"><script type="text/javascript"> var randarray = new Array(); var l=0; var flag; var numofpost=10; function nooprandomposts(json){ var total = ...

Having trouble locating the module in my Node.js application

I am encountering an issue with my application, the directory structure is as follows: myApp controllers cars.js models car.js app.js package.json In my code, I reference my model and controller in the following manner... var express = req ...

Error 400: Invalid Request: Issue encountered when swapping code for Asana access token using Next.js

Encountered a 400 Bad Request error while trying to exchange the code for an access token at . I am unsure of the cause and would appreciate any assistance. Below is the code: const GetAsanaAccessToken = async (req, res) => { const body = { grant ...

What is the method to spin an item in three js while keeping its axis in focus?

Looking to rotate a globe object around its y-axis smoothly? I have come across a helpful function for achieving this: function rotateAroundObjectAxis(object, axis, radians) { var rotationMatrix = new THREE.Matrix4(); rotationMatrix.makeRotationAxis ...

Uninstalling Puppeteer from npm can be done by running a

Some time ago, I had integrated Puppeteer into an Express API on Heroku using their Git CLI. Recently, I decided to remove Puppeteer from the package.json file and went through the npm install process before trying to push to GitHub. However, it appears th ...

Creating a text file while in a suspended state within the event handler on Windows 8 using HTML5

When the suspend event is triggered inside the winjs.application.oncheckpoint event handler, I am attempting to write a text file. The content of the file is my object in JSON format. Below is the code snippet: applicationData.localFolder.createFileAsync( ...

Displaying the value of a jquery variable in an HTML document

I'm tackling a problem differently today compared to yesterday, but my knowledge of jQuery and JavaScript is quite basic. My goal is to increment the transform value of a div every 5 seconds: <div style="transform: translateX(0px);" id="slide_ima ...

Ways to apply the margin-top property to create space between an input field and

I have been experimenting with Vue and I created a simple code snippet. <template> <div> <input /> <span class="span-text">Hi</span> </div> </template> // index.css .span{ margin-top: 3px; } I a ...

Importing a file using its absolute path in JavaScript

Within the dependencies directory, there exists a module named foo: import foo from '../dependencies/foo'; // This import statement works as intended The challenge arises when attempting to import from a different path due to deployment in an AW ...

Unveiling the mystery: Locating the position of an element within a multidimensional array using JavaScript or JQuery

How can I retrieve the index of a specific element in a JSON array converted from a PHP array using json_encode, using JavaScript or JQuery? Initially, the user will choose an option where the values correspond to people's IDs. <select class="for ...

Tips for determining whether the current request is an AJAX request in MVC3 view using JavaScript

I have a div with a maximum height and overflow set to auto. When the size of the div overflows, a scroll bar is automatically added. However, I have also set $("#itemsdiv").scrollTop(10000); so that the scroll bar is always at the bottom. Now, I want t ...

After a certain period of time, the NodeJs exec() function ceases to create additional

I am in the process of developing a BLE scan module on nodeJs using Bluez. Below is the code snippet I have implemented: exec('sudo hcitool lescan --duplicates &', function (error, stdout, stderr) { }); exec('sudo hcitool lescan --dupl ...

Exploring the world of CouchDB through jQuery and AJAX POST requests while navigating

I am in the process of building a simple web application. Today, I installed Couch 1.3.1 and set up a database. I am currently trying to save a document to my local Couch (localhost:5984) using a POST request from a client browser that is also on localhost ...

Sending a unicode PHP variable to JavaScript is a breeze

I am attempting to transfer the titles and excerpts of Persian Wordpress posts to JavaScript. Below is the code in a .php script file: function change(){ document.getElementById("link").innerHTML = '<a href="$links[2]">$titles[2]< ...

Utilize the power of React and Framer Motion to create a visually stunning fade

After creating a preloader that appears when the variable "loading" is set to true, I now want the loader to fade out. This is an overview of my files: On the home page with all the content: return ( <> {loading ? ( ...

Swapping values between HTML tables and arrays with the power of JavaScript

I have a unique table structure that I need help with: https://i.sstatic.net/fr7oJ.png My current table has 2 rows and multiple columns, but I want to change it to have 2 columns and multiple rows like this: https://i.sstatic.net/uhkp9.png To create th ...

Error message: "When using selenium-webdriver in JavaScript, the findElement method for <a> tags cannot be used as a function."&

Seeking the website URL for brand information from this website, I attempted to retrieve it using JavaScript in the console: document.getElementById('phone_number').getElementsByTagName('a')[1].getAttribute('href') However, ...