`Automatic toggling between two inputs with adjustable settings`

There are 2 input fields in my code that only accept positive floats with 2 decimals. Any other characters entered should be automatically removed using the change() function.

Whenever the value of one input is changed, the value of the other input should also change automatically.


Error #1 - Main issue

The regular expression used does not restrict the number of decimal places to 2 and allows multiple periods (eg: 12.345.67 is accepted).

Error #2

The forbidden characters are not properly removed when calling the change() function, resulting in the following error message:

Error: $scope.uc.replace is not a function

This error occurs because replace() can only be applied to strings while math operators (+, -, *, /) work only with numbers. How can I resolve this conflict?


You can view and test my code on this JSFiddle link.

var myApp = angular.module('myApp',[]);

function MyCtrl($scope) {
    $scope.coeff = 0.5;
    $scope.uf = '25';
    $scope.uc = '';
    
    $scope.change = function(type) {
        console.log(type, "changes!");
        
        $scope.uf = $scope.uf.replace(',', '.');
        $scope.uf = $scope.uf.replace(/[^\d.-]/g, '');
        $scope.uc = $scope.uc.replace(',', '.');
        $scope.uc = $scope.uc.replace(/[^\d.-]/g, '');
        
        if(type == 'uf') {
            $scope.uc = $scope.uf * $scope.coeff;
        } else if(type == 'uc') {
            $scope.uf = $scope.uc / $scope.coeff;
        }
    }
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="myApp" ng-controller="MyCtrl">
  <input type="text" ng-model="uf" ng-change="change('uf')"/>
  <input type="text" ng-model="uc" ng-change="change('uc')"/>
</div>

Answer №1

Have you considered using the input type="number" instead? Check out this demo: http://jsfiddle.net/Lvc0u55v/7192/

<div ng-controller="MyCtrl">
  <input type="number" step="0.01" ng-model="uf" ng-change="change('uf')"/>
  <input type="number" step="0.01" ng-model="uc" ng-change="change('uc')"/>
</div>

var myApp = angular.module('myApp',[]);

function MyCtrl($scope) {
    $scope.coeff = 0.5;
    $scope.uf = "25";
    $scope.uc = "";

    $scope.change = function(type) {
        console.log(type, "changes!");

        if(type == 'uf') {
            $scope.uc = $scope.uf * $scope.coeff;
        } else if(type == 'uc') {
            $scope.uf = $scope.uc / $scope.coeff;
              }
    }
}

Answer №2

When addressing Problem #1, the solution involves using a regex that precisely filters out unwanted elements:

$scope.uf = $scope.uf.replace(',', '.')
                     .replace(/[^\d.]/g, '')
                     .replace(/\./, "x")
                     .replace(/\./g, "")
                     .replace(/x/, ".");

To tackle Issue #2, the calculation can be performed using the parseFloat method:

$scope.uc = +parseFloat($scope.uf * $scope.coeff).toFixed(2);
$scope.uf = +parseFloat($scope.uf = $scope.uc / $scope.coeff).toFixed(2);

The usage of toFixed(2) limits the decimals to two after the point.


A custom directive is then utilized for float validation in the code:

angular.module('myApp').directive('floatOnly', function() {
    return {
        require: 'ngModel',
        restrict: 'A',
        link: function(scope, element, attrs, modelCtrl) {
            modelCtrl.$parsers.push(function(inputValue) {
                if(inputValue === undefined) return '';

                cleanInputValue = inputValue.replace(',', '.')
                                            .replace(/[^\d.]/g, '')
                                            .replace(/\./, "x")
                                            .replace(/\./g, "")
                                            .replace(/x/, ".");
                if(cleanInputValue != inputValue) {
                    modelCtrl.$setViewValue(cleanInputValue);
                    modelCtrl.$render();
                }
                return cleanInputValue;
            });
        }
    }
});

This directive is implemented in HTML as follows:

<div ng-controller="MyCtrl">
  <input type="text" ng-model="uf" ng-change="change('uf')" float-only/>
  <input type="text" ng-model="uc" ng-change="change('uc')" float-only/>
</div>

Therefore, the change() function now functions like this:

$scope.change = function(type) {
    console.log(type, "changes!");
  
    if(type == 'uf') {
        $scope.uc = +parseFloat($scope.uf * $scope.coeff).toFixed(2);
    } else if(type == 'uc') {
       $scope.uf = +parseFloat($scope.uf = $scope.uc / $scope.coeff).toFixed(2);
    }
 }

Link to Functional Demo

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 queries for directions on Google Maps are resulting in the same response being returned for all requests

I've been experimenting with the Google Maps Directions service to retrieve three different travel methods for the same route (driving, walking, and bicycling). Despite successfully iterating through the array of methods and setting them in the respec ...

Error: The JSON in app.js is invalid due to the unexpected token "C" at position 0

When I try to run this code snippet, I sometimes encounter an error message that says: SyntaxError: Unexpected token C in JSON at position 0. function fetchData(user_country) { fetch(`https://covid19-monitor-pro.p.rapidapi.com/coronavirus/cases_by_day ...

Differences Between JavaScript and TypeScript Classes

I'm a novice when it comes to TypeScript and JavaScript classes! While learning TypeScript, I created a simple code snippet like this: class User { name: string; email: string; constructor(name: string, email: string) { this.name = name; ...

Using Vue JS to showcase array data in a dropdown menu with Bootstrap-vue

Currently, I have an array of JSON data structured like this: loggers = [{ "allAvailableLevel": ['WARN', 'DEBUG', 'INFO'], "level": "WARN", "logger": "com.test1", "status": "success" }, { ...

The reactivity of a Vue.js computed property diminishes when it is transmitted through an event handler

Within my main application, I've implemented a Modal component that receives content via an event whenever a modal needs to be displayed. The Modal content consists of a list with an associated action for each item, such as "select" or "remove": Vue. ...

Experiencing inaccuracies in Magento's item validation process when checking the quantity of items being added to the cart

Upon entering a text string in the quantity field of the "Add to Cart" input box, Magento does not display an error message but instead considers it as a quantity of "1". Is there a way to modify this behavior and have the validation system mark strings ...

Issue with React component not displaying in the browser.Here are some

I am currently following a React tutorial on and I'm facing an issue where the Counter component is not displaying on the page. The generated HTML looks like this: <html> <head> <script src="/bundle.js" ></script> </he ...

How long does it take to delete and recreate a cloudfront distribution using AWS CDK?

I am currently undergoing the process of migrating from the AWS CDK CloudfrontWebDistribution construct to the Distribution Construct. According to the documentation, the CDK will delete and recreate the distribution. I am curious about the total duration ...

Prevent Fixed Gridview Header from being affected by browser Scroll-bar using JQuery

Is there a way to make the fixed header responsive to only one scroll bar in JQuery? Specifically, is it possible to have it respond solely to the div's scroll bar and not the browser's scroll bar? I attempted to remove the browser's scroll ...

Tips for retrying an insertion into the database when a duplicate unique value is already present

After thorough searching, I couldn't find any existing patterns. My goal is to store a unique key value in my MySQL database. I generate it on the server side using this code: var pc = require('password-creator'); var key = pc.create(20); ...

Steps for adjusting the length in the getRangeLabel function of mat paginator

@Injectable() export class MyCustomPaginatorIntl extends MatPaginatorIntl { public getRangeLabel = (page: number, pageSize: number, length: number): string => { if (length === 0 || pageSize === 0) { return `${ ...

An issue arose while trying to create the perfect seed with yeoman

While working on my first Yeoman webapp using the ultimate-seed-generator, I encountered some errors that are hindering progress: C:\Users\Fidel\Desktop\Nueva carpeta\new-proyect>npm install > <a href="/cdn-cgi/l/email ...

Why isn't the onChange function triggering in the input type text when the input is not manually typed in?

I am currently facing an issue with two text fields in my HTML form. Here is how they are set up: HTML : <input type="text" id="input1" onchange="doSomething();" disabled/> <input type="text" id="input2"/> JavaScript : function doSomething( ...

Why is the editor not displaying the correct line number when the enter key is pressed repeatedly in JavaScript?

I am currently working on developing an editor using JavaScript. My goal is to display a line count (e.g., 1, 2, 3) whenever the user presses 'Enter' to change lines. I have successfully managed to count the line changes upon pressing 'Enter ...

Next.js version 13 is causing the page to refresh each time the router is pushed

I am currently developing a search application using NextJs 13, and I have encountered an issue where the page refreshes every time I click the search button. Strangely, this only happens when the application is deployed on Vercel. When running the app l ...

What is the process for extracting an object from an array?

As a newcomer to jQuery, I've encountered an issue that has me stuck. My problem lies in accessing an array within an object. Here's the structure of my object as shown during debugging: cache:object 0001-:Array[2] 0:value1, ...

Tips for optimizing Angular source code to render HTML for better SEO performance

Our web platform utilizes Angular JS for the front-end and node js for the backend, creating dynamic pages. When inspecting the code by viewing the source, it appears like this: For our business to succeed, our website needs to be SEO-friendly in order to ...

Tips for adding one document to two separate collections using JavaScript and MongoJS

Having trouble inserting data into two separate tables using javascript and mongojs. While I was able to successfully insert into a single collection by following the npm mongojs documentation, I couldn't find a solution for multiple collections on th ...

Utilizing the current state within a React callback function closure: A guide to maximising efficiency

I'm currently working on a web page that features a dynamic list of form inputs. Users have the ability to add or remove input fields using designated buttons. To manage this functionality, I've created a parent object called <Ingredients /> ...

Exploring the Power of AngularJS Directives within MVC 5.0

Is there a way to implement the [numericOnly] directive in a textbox using Razor? @Html.TextBoxFor(m => m.salary, new { data_ng_model = "salary" }) app.directive('numericOnly', function () { return { restrict: 'A', ...