Variation in the distribution of input values

I have a challenge I'm working on that involves two main objectives:

  1. My goal is to distribute the total sum of 3 input values evenly so they add up to 100.

    $input1 = $('#input1 ');
    $input2 = $('#input2 ');
    $input3 = $('#input3 ');
    
    $input1.on('input', function () {
            $input2 .val(100 - this.value);
            $input3 .val(100 - this.value -  $input2.value)
    });
    

    Although $input2 is displaying correctly, it's not passing its value onto $input3, resulting in NaN.

    I also attempted creating a callback for input3, but encountered issues with that as well.

  2. I am also trying to figure out how to prevent users from entering numbers outside the range of 0-100.

Check out my JSFiddle here

Answer №1

Consider transitioning away from jQuery as it can lead to confusion between the DOM API and jQuery API. It's important to focus on learning the fundamentals of the DOM rather than relying solely on jQuery.

let $input1 = document.querySelector('#input1');
let $input2 = document.querySelector('#input2');
let $input3 = document.querySelector('#input3');

$input1.addEventListener('input', function () {
            $input2.value = (100 - this.value)/2;
            $input3.value = 100 - this.value -  $input2.value;
        });
<form>
<input id='input1'/><br/>
<input id='input2'/><br/>
<input id='input3'/>
</form>

Answer №2

$input2 is actually a jQuery wrapped element, so you can't simply call value on it directly. Instead, you should use val() to retrieve the value. If you try using value, it will result in NaN.

Make this adjustment:

$input3.val(100 - this.value - $input2.value)

to this:

$input3.val(100 - this.value - $input2.val())

Another approach would be to extract the native element from the jQuery wrapper and then access its value. This alternative method should also work smoothly:

$input3.val(100 - this.value - $input2[0].value)

In case of #2, consider utilizing input[type=number] and setting limits with the help of min and max attributes.

Answer №3

To achieve the desired outcome, it is important to utilize $input2.val() or $input2[0].value. The alignment of values in both input2 and input3 fields can be executed in the following way.

$input1 = $('#input1 ');
$input2 = $('#input2 ');
$input3 = $('#input3 ');

$input1.on('input', function() {
  $input2.val(parseInt((100 - this.value) / 2));
  $input3.val(100 - this.value - $input2.val())
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<input id="input1" type=number min="0" max="100">
<input id="input2" type=number min="0" max="100">
<input id="input3" type=number min="0" max="100">

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

What is the best way to access a variable in one file and then utilize it in multiple other files?

My question may seem straightforward, but I'm having trouble finding the right solution. Within my index.html file, I have the following content: <html> <head> <script src="scalar.js"></script> </head> <body> < ...

Load an external URL and load a file from the local directory using Electron

For an upcoming art exhibition, I have a video installation that consists of large videos (several GBs) and an online hosted web application. To conserve bandwidth during the exhibition, I am considering packaging the videos into an electron app. This way ...

Discovering the `findIndex` malfunction in Internet Explorer

Having just finished a small form, I realized that my current implementation of findIndex is not compatible with IE. Let's take a look at an example of the problem: var people = [ {name:"Mike", age:"25"}, {name:"Bill", age:"35"}, {name:"Terry" ...

What are some techniques for generating unique level combinations from a multi-dimensional array?

How can I efficiently combine multiple arrays and permute them without including any single array itself? Additionally, I need to combine and permute them into 2D/3D/4D-arrays. Any assistance is appreciated. var arr1 = ['a', 'b']; var a ...

Avoid continuing navigation if a different link is selected in Angular

My Angular form automatically redirects to the homepage after a certain number of seconds when submitted. Below is the service responsible for the redirection: export class RouterService { private unsubscribe: Subject<void> = new Subject(); cons ...

Modifying data-iconpos Dynamically with jQuery Mobile

Currently, I am developing a jQuery Mobile app and I am facing an issue. I want to have the ability to change the attributes of navbars across multiple HTML files using a single function in a separate .js file. I attempted to modify the class during page c ...

Obtain file information using an AJAX call in Ruby on Rails 3

Recently, I discovered a limitation in downloading multiple files with a single HTTP request in Ruby on Rails, unless I use AJAX. Now, I am exploring how to overcome this challenge. (I am utilizing Prawn as a PDF creator in Ruby on Rails 3). In my control ...

Is it possible for an object to receive notifications when a component object undergoes changes in Angular 2/4?

When working with Angular components, it's possible to pass a variable or object as @Input(). The component will be notified whenever the value of this input changes, which is pretty cool... I'm currently developing an application that features ...

Modifying the position of a component in the UI tree to reset its state in ReactJs

According to React, the state will be maintained as long as the same component is rendered at the same position. In this scenario, I have two Counter components rendering. By toggling a checkbox, I am able to control the visibility of the first Counter co ...

removing duplicate items from an array in Vue.js

I created a Pokemon App where users can add Pokemon to their 'pokedex'. The app takes a pokemon object from this.$store.state.pokemon and adds it to this.$store.state.pokedex. However, users can add the same pokemon multiple times to the pokedex, ...

Having difficulty exporting data using my current method in Excel

While rendering with condition, I encountered an issue attempting to export data for searchOrderBy. The error message received was "TypeError: Cannot read property 'forEach' of undefined." Currently, only theDataSet data is functional for Excel ...

ng-option featuring a stationary link option

How can I create a static option that links to another page using ng-options? <select class="form-control" ng-model="person" ng-options="person.name for person in persons"> </select> I am trying to use the select element with ...

provide the key and id to a node.js module

Currently, I am utilizing the Express framework to establish a module for handling requests to a third-party API. This particular API necessitates an ID and key to be transmitted. Rather than embedding these credentials directly into the module, I prefer ...

Tips for transferring data from a JavaScript page to a C# page by utilizing Jquery

I am working with a dynamically created table that contains values in its selected rows. I need to extract all td.innerText values from each selected row and send them to a C# page, but I am unsure of the best approach. I attempted to use JSON, but I am ...

The latest URL is not launching in a separate tab

Looking for some assistance with this code snippet: <b-btn variant="primary" class="btn-sm" :disabled="updatePending || !row.enabled" @click="changeState(row, row.dt ? 'activate' : 'start&apo ...

Gathering names by clicking a button to reveal additional names on a webpage

I was presented with an interesting challenge by a coworker earlier, and I must admit that I'm a bit stumped on how to approach it. Essentially, the task involves a website containing a list of names (). My colleague needs to gather all these names ...

Having trouble extracting the ID from the URL using parameters

Just diving into the world of Express JS and MongoDB, so I appreciate your patience with me. Currently following a web development tutorial by Colt Steele. Take a look at my code: app.get("/:id",async(req,res)=> { const id= req.params[&apo ...

Attempting to retrieve data from an object by utilizing an external URL, however

Upon starting the bot console, the console displays: Online with undefined/5 After 10 seconds, an error is thrown: undefined:1 [object Promise] ^ SyntaxError: Unexpected token o in JSON at position 1 This is the code snippet being used: let players clie ...

Troubleshooting the issue with UI-Router AngularJS controller not functioning properly in a

Trying to grasp the ins and outs of UI-Router in conjunction with Angular has proven to be quite challenging for me. In my setup, there's an index: <body> <div ui-view></div> <!--Location of file holding app--> <scri ...

Updating FieldArray elements with Redux store variable can be done by following these steps:

I'm currently utilizing redux-form with a FieldArray. By default, the array contains 1 element that is populated from JSON. The FieldArray component allows me to add up to 3 elements. In the code below, the 'elementList' property is sourced ...