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

How to create a looping animation effect for a div using CSS on hover

Using Bootstrap framework with Wordpress site .test { position: absolute; z-index: 9; left: 50%; height: 10em; width: 10em; margin-left: -5em; background-size: cover; opacity: 0; transition: opacity 0.5s ease; transform: translateY(- ...

Switch up the like button for users who have previously liked a post

Greetings, I trust everything is going well. I am attempting to implement a feature where users can like a post or article created by others using a button. I have established a const function named "getAPostLikeRecord()," which retrieves a list of users w ...

A step-by-step guide to accessing Chrome performance metrics using JavaScript

By utilizing Chrome Dev Tools, I am able to perform the following actions: Begin by opening Chrome Dev Tools (simply right click on any page in Chrome and select "inspect") Navigate to the "performance" tab Click on the record button Interact with a butt ...

Tips for populating countryList data in Form.Select component within a React.js application

I have a data file that contains a list of all countries, and I need to display these countries in a select input field, similar to what you see on popular websites when a user logs in and edits their profile information like name, address, and country. H ...

Is searching for duplicate entries in an array using a specific key?

Below is an array structure: [ { "Date": "2020-07", "data": [ { "id": "35ebd073-600c-4be4-a750-41c4be5ed24a", "Date": "2020-07-03T00:00:00.000Z", ...

AngularJS - Always keep an eye on a group of items

Looking to create a custom watcher for a collection within my application, I initially believed that Angular would have all the necessary tools at my disposal. I had access to $watch, both shallow and deep, as well as $watchCollection. A $digest cycle was ...

What is the best way to verify the presence of a value in an SQL column?

I need to check if a value exists in a column. If the value already exists, I do not want to insert it into the table. However, if it does not exist, then I want to add new data. Unfortunately, my attempted solution hasn't been successful. You can fi ...

Issue with Vuejs where changes are made to the parent array, but the child component does not detect those

I'm facing an issue where my parent component has the following code: {{ fencing }} <FencingTable v-if="fencing.length > 0" :fencing="fencing" :facility="facility" /> get fencing() { return this.$sto ...

What is the best strategy for managing pagination when dealing with a large number of pages?

Up until now, I have understood that pagination only links different pages together. This works fine when dealing with a limited number of pages or posts to display. However, what if I have 30 or more pages to paginate? Wouldn't it be impractical to c ...

Tried to enroll the RCTBridgeModule category as RCTFileReaderModule

Trying to register the RCTBridgeModule class RCTFileReaderModule with the name 'FileReaderModule' failed because the name was already taken by the FileReaderModule class. This issue arises when attempting to launch an application on iOS using th ...

Do we need to use aria-labelledby if we already have label and input associated with "for" and "id"?

Here is the HTML structure for the Text Field component from Adobe Spectrum: The <label> element has a for attribute and the <input> has an id which allows screen readers to read out the label when the input is focused. So, why is aria-label ...

The jQuery onClick function functions effectively for the initial two clicks; however, it ceases to

I am currently experimenting with jQuery to dynamically load a specific div from another page on my server into a designated section on the existing page. While the code is successfully functioning for the first two clicks on the website, it fails to work ...

Retrieve the structure from a React application

When it comes to documenting architecture, the process can be incredibly beneficial but also quite time-consuming and prone to becoming outdated quickly. I have come across tools like Doxygen that are able to extract architectural details such as dependen ...

Utilizing GeoLocation in JavaScript: Implementing a Wait for $.ajax Response

Whenever I make an AJAX POST request to my backend server, I aim to include the latitude and longitude obtained from the navigator. However, it seems like the request is being sent in the background without waiting for the navigator to complete its task. ...

Express along with Cheerio and JSDOM

I'm currently exploring the integration of Cheerio with Express to enable server-side DOM manipulation. I haven't had much luck beyond basic web scraping techniques. There are specific requirements I need to meet for this project. Currently, I ...

Personalize JSON Reporter to Display Captured Information - WebdriverIO

I'm currently in the process of scraping data from an android app using WDIO and APPIUM. After successfully storing the scraped data in an array, I now aim to automatically output this array data to a .json file, rather than manually copying and pasti ...

Why are the buttons on my HTML/JavaScript page not functioning properly?

I have been struggling with a code for a 5 image slideshow where the NEXT and PREVIOUS buttons are supposed to take me to the next and previous slides. However, when I press them, nothing happens. Can anyone provide some assistance? I need additional detai ...

Tips for shifting a div to the left with AngularJS

I am working with a div structure that looks like the following: <div class="col-xs-1 scroll-button"><i class="glyphicon glyphicon-chevron-left"></i> </div> <div class="customer-ust-bant col-xs-22" id="letters"> <box n ...

Recording Audio Using ReactJS

I am exploring ways to record audio using ReactJS and save it on my Node server. Initially, I attempted to utilize the "react-audio-recorder" module but encountered issues when attempting to record multiple audios consecutively. Additionally, I experiment ...

Guide on transferring a JWT token to a Node.js backend

Recently, I developed a node.js server featuring a login system and am focused on safeguarding my routes. Despite creating middleware to authenticate each protected route, I keep encountering an "Authentication failed" message after logging in. How can I e ...