Is there a way to automatically change the value of one input box to its negative counterpart when either of the two input boxes have been filled in?

Consider two input boxes:

  1. box1
  2. box2

If a user enters a number in one of the input boxes, we want the value of the other input box to automatically change to the opposite sign of that number.

For example:

  • User enters 3 in box1. The value of box2 should change to -3.
  • User enters -5 in box1. The value of box2 should change to 5.

How can we implement this functionality using AngularJS 1.x?

Answer №1

Here are a couple of methods to achieve this:

  1. To start, you can add a watch in your controller for the values of num1 and num2. It would look something like this (assuming $scope is injected into your controller)

Sample HTML

<input type="number" ng-model="num1">
<input type="number" ng-model="num2">

Sample JS

$scope.$watch('num1', function(newVal){
  $scope.num2 = -newVal;
}

$scope.$watch('num2', function(newVal){
  $scope.num1 = -newVal;
}

This method is recommended if you plan on using the controller with multiple views or if there is a relationship between the model data (num1 and num2). The watches will trigger whenever the numbers change for any reason (other bindings, manual changes in JavaScript, etc).

  1. Alternatively, you can use ng-change on your input fields to set the value in an angular expression

Sample HTML

<input type="number" ng-model="num1" ng-change="num2=-num1">
<input type="number" ng-model="num2" ng-change="num1=-num2">

This approach is ideal if you only need to focus on one number, or if this logic specifically belongs in the view. It may also be more efficient as it listens for the change event instead of checking for equivalence every digest cycle. However, keep in mind that if either number changes through means other than altering the input field directly, the change will not be reflected. Thanks to Manatax for highlighting most of these benefits in the comments below.

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

Im testing the creation of a global style using styled-components

Is there a way to create snapshot tests for styled-components with createGlobalStyle? The testing environment includes jest v22.4.4, styled-components v4.1.2, react v16.7, jest-styled-components v5.0.1, and react-test-renderer v16.6.3 Currently, the outp ...

The component contains a render method, however, it does not inherit from React.Component

A component is displaying a render method, however it does not extend React.Component. This may lead to potential errors. Please modify <Test> to extend React.Component instead. When utilizing the extends-classes library, it results in a react compo ...

Refresh ng-repeat array after implementing filter in controller

I am currently facing an issue with updating my table view when changing a variable that filters an array. The filter is applied in the controller based on the values of a specific variable called columnFilter. However, the filter does not reapply to updat ...

Vue's smooth scrolling in Nuxt.js was not defined due to an error with the Window

There seems to be an issue with adding vue smooth scroll to my nuxt.js project as I'm encountering the "window is not defined error". The steps I followed were: yarn add vue2-smooth-scroll Within the vue file, I included: import Vue from 'vue ...

Would it be frowned upon in JavaScript to use "if (somestring in {'oneoption':false, 'secondoption':false})"?

Is the use of this construct considered a bad practice in JavaScript and could it lead to unexpected behavior? if (e.target.name in {name: '', number: ''}) { // do something } This code checks if the 'name' attribute of an ...

Step-by-step guide on integrating a specific location into Google Maps using React.js

I'm in the process of revamping my website using Reactjs. I want to incorporate a specific Google location with reviews on the map, similar to how it appears on this example (My current website is built on Wordpress). As of now, all I've been ab ...

Enhancing Website Interactivity with PHP, AJAX, and

I recently followed a tutorial on handling AJAX requests with PHP and MySQL, which can be found here. My goal is to update the SQL query based on the value selected from a dropdown menu using the onchange event. function myfunctionTime(time) { if (t ...

Is there a way to generate bootstrap divs by parsing csv text?

As I am working on a Bootstrap 3 image gallery, I have noticed that there are multiple recurring divs with a similar structure as shown below: <figure class="col-1 picture-item" data-groups='["groupA"]' data-date-created="2018" data-title=" ...

Express route not capturing entire request parameter due to regex issue

I am pretty sure that the issue lies in how express handles regex patterns in route definitions, although it might also be related to my pattern (I'm still new to regex, so please bear with me). In my express route definition, I am attempting to match ...

Error message encountered in Rails Webpacker: "Uncaught TypeError: $(...).tooltip is not recognized as a function

I am working on a Rails 6 application where I compile assets using Webpack 4.39.1 with the help of the Webpacker gem. In my webpack configuration file (config/webpack/environment.js), I have included JQuery 3.4.1 and Popper.js as part of the ProvidePlugin ...

Click on the links to view various captions for a single image, one at a time

My goal is to create an interactive image similar to what can be found at . (Click Play and navigate to page 5 to see the interactive physical exam). While this example seems to use Flash, I am interested in achieving a similar effect using javascript/jQue ...

Extract the price value from the span element, then multiply it by a certain number before adding it to a div element

On the checkout page of my website, I have the following HTML: <tr class="order-total"> <th>Total</th> <td><strong><span class="woocommerce-Price-amount amount"> <span class="w ...

The AJAX call to retrieve data from a file dynamically is experiencing issues

I am currently trying to use AJAX to dynamically retrieve data from my PHP page and display it on my HTML page. However, I am running into some issues with getting it to work properly. You can view the page here Here is the snippet from the HTML Page wher ...

Utilize a singular ng-model for efficiently filtering and presenting filtered data

Recently, I encountered an issue with a HTML select element that is used to sort a list. The code for the select element looks like this: <select ng-init="sortMethod=sortMethods[0]" ng-model="sortMethod"> <option ng-repeat="sortMethod in sortMe ...

How can I change the background color of a parent div when hovering over a child element using JavaScript

I am working on a task that involves three colored boxes within a div, each with a different color. The goal is to change the background-color of the parent div to match the color of the box being hovered over. CSS: .t1_colors { float: left; wid ...

Utilizing AngularJS, implement ng-form and ng-repeat to seamlessly handle input validation and submission actions

Angular 1.6.2 I am experimenting with iterating over elements of a collection inputted by the user, checking their validity, and enabling the submit action if validation passes. I have tried using ng-form for this purpose and have come up with two differ ...

What discrepancies exist between running npm install on Windows versus Linux operating systems?

Just have a quick question to ask. I've been searching online with no luck. If I were to run npm install on a Windows machine to set up my dependencies, would it be viable to transfer the node_modules directory to a Linux machine and execute my nodej ...

A simple way to verify which option has been chosen has been altered

I am examining the code snippet below: <select class="select" id="choice-item" aria-invalid="false"> <option value="#opt0" selected="selected">32 bits</option> <option value="#opt1">64 bits</option> </select> M ...

Angular Selectable Drop-down Menu

I'm facing an issue with using angularjs for dropdown with multiple selection. When I try to include 2 dropdowns in the same form, only one of them gets initialized properly. Here is a sample code snippet http://jsfiddle.net/vUSPu/1221/. Can someone p ...

Error occurred when attempting to fetch data from a nested JSON object in React/Next.JS

Having trouble retrieving data from my API and encountering this error message. I suspect it may be related to the JSON structure. Interestingly, when using a different URL with nested arrays, it works fine. However, my current data is not cooperating. Any ...