Performing computations using data entered into form fields

Need some assistance from the Vue experts out there. I am diving into Vue as a beginner and trying to create a simple calculator.

The issue at hand is having three input forms where two values are entered and the third calculates the result.

Ideally, I want all three forms to be blank initially and once data is entered in any two, the calculation should display in the third field. The order of entry shouldn't matter. However, I struggled with this logic and ended up hardcoding the values for now. I need a dynamic solution where any two values will always calculate the correct result in the third field.

Moreover, my current code contains multiple if statements which I know can be optimized for better coding practices. Though it currently works fine, I anticipate it getting lengthy with more if statements added.

new Vue({
  el: "#app",
  data: {
    value1: null,
    value2: null
  },
  computed: {
    a_ratio() {
      var a_number = parseInt(this.value2) / parseInt(this.value1);
      return a_number.toFixed(1);
    },

    calculation() {
      if (this.value1 < 100 && this.value2 > 0) {
        var val = parseInt(this.value2) / 10 || 0;
        return val.toFixed(1);
      }
      if (this.value1 >= 100 && this.value2 > 0) {
        var val = parseInt(this.value2) / 20 || 0;
        return val.toFixed(1);
      }
    }
  }
});

Answer №1

Visually more appealing :)

new Vue({
  el: "#app",
  data: {
    value1: null,
    value2: null
  },
  computed: {
    a_ratio() {
      var a_number = parseInt(this.value2) / parseInt(this.value1);
      return a_number.toFixed(1);
    },

    calculation() {
      if (this.value2 <= 0) return;
      let divider;

      if (this.value1 < 100) {
        divider = 10;
      } else if (this.value1 >= 100) {
        divider = 20;
      }

      return (parseInt(this.value2) / divider || 0).toFixed(1);
    }
  }
});

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

When using React, draggable components with input fields may lose their ability to receive focus when clicking on the input field

<Draggable axis="y" grid={[135,135]} onStop={this.handleStop} defaultPosition={{x: this.props.task.positionX, y: this.props.task.positionY,}}> <div id="edit-task-component"> <form onSubmit={this.handleSubmit} id=" ...

Guide to updating a vue.js array using user input values

I am currently developing a web application that includes a table displaying information from an array created using vue.js. The goal is to allow editing, updating, and deleting content in the array based on the requirements of an admin account, which woul ...

Refreshing a Web Page with JavaScript

I'm currently facing an issue with my Rails application that includes JavaScript. The JavaScript works fine when the document is initially loaded, but I need it to reload whenever a new page is visited. Is there a way to achieve this without having to ...

Arrange SVGs using CSS in a grid with offsets

My current project involves creating a background using SVGs in React. I'm looking for an easy CSS method to arrange these icons in a grid, possibly with an offset for the second row. I also need the width of the icons to be dynamic so that they adj ...

Is there an npm module available that can automate a daily task at a specified time in a Node.js environment?

Searching for an NPM Module to integrate into a Node.js application that can send notifications via email and SMS daily at 9am local time. Any suggestions or solutions would be greatly appreciated! ...

"Troubleshooting: Why Isn't My jQuery Ajax PUT

This ajax script functions perfectly in Chrome, utilizing HTTP PUT to add an object to a RESTful API. $.ajax({ type: "PUT", url: "/ajax/rest/team/create/", dataType: "json", processData: false, ...

Query to collect all user data using a WHERE clause

I recently started working with Firebase and have encountered an issue regarding the use of the 'where' clause. Here is a sample of the JSON data I'm dealing with: Users | |_____ John | |___ name: John Farmer | |___ searching ...

How can I retrieve information from an object using Mongoose queries?

Looking to retrieve data for all users with cardNumber: 3243 using the provided mongoose model. cred: { nameValue: 'anonymous', emailValue: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1879767776617 ...

Set up a programmatic way to manage errors in Vue using Mocha

In almost all of my unit tests in Mocha, I consistently include the following code snippet at the beginning: it('should do something', (done) => { Vue.config.errorHandler = done; // perform some asynchronous action }); By default, Vue h ...

Retrieve targeted information from the API upon hitting the ENTER key

I am currently working on a feature that involves returning specific data when the Enter key is pressed, similar to a barcode scanner. The idea is that after scanning a barcode, which triggers the Enter key code (keyCode = 13), the application should searc ...

Generating a JSON object by parsing a JSON file

I'm encountering an issue when trying to retrieve movie information by sending a GET request to omdbapi.com. Below is the code snippet responsible for handling POST requests to my database: const express = require('express'); const router ...

Refresh the array using Composition API

Currently, I am working on a project that utilizes Vue along with Pinia store. export default { setup() { let rows: Row[] = store.history.rows; } } Everything is functioning properly at the moment, but there is a specific scenario where I need to ...

The function of modal in JavaScript is not working properly

I am encountering a problem with my web page that is running on Wildfly 12. It is a simple Java EE project that I developed in Eclipse Neon. The issue arises when I try to use Bootstrap modals, as every time I attempt to open or use the methods in a JavaSc ...

How can one achieve an explosion effect using jQuery?

Hey there! Here's a question to ponder... Let's assume we have a JavaScript variable set up like this: let myString = 'x,y,z'; let separated = myString.split(','); Now, imagine we have an HTML element like this: <ul id= ...

Refreshing a webpage post initial loading using Next.js

Having trouble with my checkout route ""./checkout"" that displays embedded elements from Xola. The issue arises when using client-side routing as the checkout page requires a manual refresh to load correctly and show the Xola elements on the DOM ...

How can I conceal the range input button in Bootstrap 4?

Below is the html code snippet that I currently have: <form> <div class="form-group"> <label for="formControlRange">Example Range input</label> <input type="range" class="form-control-range" id="formControlRange"> ...

Is there a way to utilize Selenium in Python to access and read the local storage of my Safari Web Extension?

Using the Firefox WebDriver, I am able to access the local storage of my extension in the following way: extension_path = "/path/to/my/extension" info = { "extension_id": f"foobar", "uuid": uuid.uuid4(), } b ...

Having trouble connecting to JSTL in my JavaScript file

Currently, I am facing an issue with my JSTL code that is housed within a JavaScript file being included in my JSP page. The problem arises when I place the JSTL code inside a script within the JSP page - it works perfectly fine. However, if I move the s ...

Configuring the state of a deeply nested element within a multi-level array component in ReactJS

My React application has a state element structured as follows: state = { options: { xaxis: { categories: [] } } } However, I encountered an issue when trying to set the state of the 'categories' array within the 'xaxi ...

Is it possible to utilize a jQuery function to count JSON data based on specific keys and values?

function calculateJSONObjFrequencyByKeyValue(obj, key, value) { var frequencyCount = 0; $.each(obj, function(i, item) { if(obj[i].key == value){ frequencyCount++; } }); alert(frequencyCount); } calculateJSONObjFrequencyByKeyValu ...