Is it possible to enter NaN in Vue3?

Is there a way to handle NaN values and keep a field blank instead when calculating margins with a formula? https://i.stack.imgur.com/JvIRQ.png

Template

      <form>
        <div class="row">
          <div class="mb-3 col-sm-4 col-xs-12">
            <h6 class="text-dark" for="purchasePrice">x:</h6>
            <input
              type="text"
              class="form-control"
              autocomplete="off"
              v-model="purchasePrice"
              @keypress="isNumber($event)"
            />
          </div>
          <div class="mb-3 col-sm-4 col-xs-12">
            <h6 class="text-dark" for="salePrice">y:</h6>
            <input
              type="text"
              class="form-control"
              autocomplete="off"
              v-model="salePrice"
              @keypress="isNumber($event)"
            />
          </div>
          <div class="mb-3 col-sm-4 col-xs-12">
            <h6 class="text-dark" for="marginResult">z:</h6>
            <input
              type="text"
              class="form-control"
              autocomplete="off"
              disabled
              :value="
                (
                  ((parseInt(salePrice) - parseInt(purchasePrice)) /
                    parseInt(salePrice)) *
                  100
                ).toFixed(3)
              "
            />
          </div>
        </div>
      </form>

Answer №1

Following the advice given in the comment, you can achieve the expected result with the code provided below.

     <template>
      <form>
    <div class="row">
      <div class="mb-3 col-sm-4 col-xs-12">
        <h6 class="text-dark" for="purchasePrice">x:</h6>
        <input
          type="text"
          class="form-control"
          autocomplete="off"
          v-model="purchasePrice"
          @keypress="isNumber($event)"
        />
      </div>
      <div class="mb-3 col-sm-4 col-xs-12">
        <h6 class="text-dark" for="salePrice">y:</h6>
        <input
          type="text"
          class="form-control"
          autocomplete="off"
          v-model="salePrice"
          @keypress="isNumber($event)"
        />
      </div>
      <div class="mb-3 col-sm-4 col-xs-12">
        <h6 class="text-dark" for="marginResult">z:</h6>
        <input
          type="text"
          class="form-control"
          autocomplete="off"
          disabled
           v-model="marginResult"
        />
      </div>
    </div>
  </form>
<script>
 export default {
  data() {
  return {
  purchasePrice: '',
  salePrice: '',

   }
  },

  methods: {
    isNumber(e) {
    if (e.keyCode < 48 || e.keyCode > 57) {
        e.preventDefault();
    }
    }
    },

computed: {
    marginResult() {
        return (this.salePrice - this.purchasePrice).toFixed(2);
    }
},

}
</script>

A screenshot is provided for you to verify the functionality of the code.

If you were expecting a blank output, it actually returns 0.00 but the concept remains clear.

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

Several challenges with managing date filters and formats in jqgrid

I am facing several challenges with a single column in jqGrid that is meant to handle date information: 1- The date is retrieved from the back-end and displayed as 29/03/2017 00:00:00. When I attempt to format it using formatter: "date", formatoptions: { ...

Challenges in Implementing Shadows with Animations in ThreeJS MeshDepthMaterial

I'm facing an issue where casting shadows through transparent parts of my Mesh using the MeshDepthMaterial causes the shadows of animated objects to stop moving along with the animation. You can see an example of this problem here: https://jsfiddle.n ...

Issue with Highcharts: Border of stacking bar chart not visible on the right side

When creating a stacking bar chart, I noticed that the rightmost 'box' does not have a border drawn on the right side. Is there a setting or option in Highcharts that can be used to ensure the white border line is drawn around the 75% box in the ...

What is the correct way to trigger an event specified as a string parameter in the emit() function?

My current goal is to pass the emit name as a string (for example, 'showComponent') from child to parent. I then want to trigger another emit in the emitAction(callbackName: string) function, and finally execute the showComponent() function. I&a ...

Is there a way for me to initiate another joyride adventure?

Encountering a challenge with my joyride tour - after completing one tour, I aim to commence a second. Despite attempting to trigger the second tour in the postRideCallback function, I find myself stuck in a loop with the first tour. Seeking guidance on re ...

Using Jquery .ajax to Populate Select Dropdown with JSON Data

I have put in a lot of effort but I'm not seeing any results. My JSON data, created with PHP, looks like this (with the header sent before the data): {"users":[ {"id":"3256","name":"Azad Kashmir"}, {"id":"3257","name":"Balochistan"}, {"id":"3258","na ...

Protractor encounters a TypeError when attempting to navigate with Firefox version 59 due to a cyclic object value

Our team has implemented several Protractor tests for our Angular JS application. Recently, we considered upgrading the Firefox browser to version 59 while using Selenium 3.11.0. However, after the upgrade, whenever we try to use element(by. in our tests ...

What is the best way to reduce the file size of a group of PNG images for

For my game character, I have a collection of PNG files including stand.png, run1.png, run2.png. To display a series of actions on the JavaScript canvas, I need to load these images. However, the size of each .png file adds up quickly – for example, it ...

Ensuring the timely execution of Javascript functions with Selenium before moving on

While working on creating test cases using Selenium, I encountered an issue. In one of my test cases, there is a small form and a search button on the website I'm testing. Filling the form and clicking the button are not the problem. The issue arises ...

Employ ImageMagic in a synchronous manner

Consider utilizing imagemagick Required to use imagemagick in a synchronous manner. Meaning the following code should execute only after the image conversion is complete (regardless of any errors). The only solution I can see involves using deasync: co ...

I encountered an error in the console stating that it cannot read the property tostring() in JavaScript

Having trouble with an error message: "cannot read tostring()". I've included my code below for reference: function convertRounding(nValue) { var sArr = nValue.toString("0.00000").split('.'); **var sVal = sArr[1].toString();** ...

Is there a way to limit the keys of T to only number fields, where T[keyof T] is a number

I'm looking to restrict the field parameter within this function: function calculate<T>(source: T[], field: keyof T) { for(const item of source) { } } The goal is to ensure that item[field] will always be a number. Is there a way to ac ...

NextJS: Issue: Accessing a client module from a server component is not allowed. The imported name must be passed through instead

My current NextJS setup is structured as shown below: app/page.js 'use client'; import React from 'react'; export default function Home() { return (<div>Testing</div>); } app/layout.js export const metadata = { title ...

Using Double Quotes in v-b-tooltip in Vue Bootstrap

I recently implemented the vue bootstrap tooltip feature on my website. You can find more information about it here. Currently, I have a tooltip set up like this: <label>Encoding <feather-icon icon="AlertCircleIcon" class=" ...

Passing an extra variable to the callback function in AJAX and saving the XMLHttpRequest.response as a variable

Attempting to read a local file on the server using the standard loadDoc(url, cfunc) function, my goal is to: 1) Search for a specific string in the file (getLine()); 2) If possible, save that line to a variable. For point 1, I provide a string to the c ...

The health check URL is experiencing issues: Unable to locate any routes

I am currently developing a .net Core 2.2/Angular 8 application and recently came across the HealthCheck feature. I decided to incorporate it into my application, so here is a snippet from my Startup.cs file: using HealthChecks.UI.Client; using Mi ...

Tips for resolving the error message "TypeError: Unable to access the 'length' property of undefined" in Vue

I am currently working on implementing an auto dropdown feature for a category list using the autocomplete-vue library. However, I encountered the following error: [Vue warn]: Error in mounted hook: "TypeError: Cannot read property 'length' of ...

Creating a curved edge for a shape in React Native can add a stylish and

Issue Description I am working on an app and struggling with styling the bottom navigation bar. It's more complex than what I've done before, especially the curved top edge of the white section and the area between the blue/green circle and the ...

Transmit a sequence of keys to the web browser

I'm having difficulty in sending a Shift key command followed immediately by tilde (~). I've attempted various examples, and here's one that I'm currently working on. I am testing the following scenario - selecting a specific image, t ...

An optional field has been identified as ng-invalid

In my set-up, I have created a form group using reactive forms. this.transactionForm = fb.group ({ 'location': [null, Validators.required], 'shopper': [null], 'giftMessage': [null], 'retailPrice& ...