Experiencing issues with receiving null values while trying to display variances from a dropdown selection? (Using JavaScript

I am in search of a solution to create a user-friendly nutrition calculator that can analyze the variance between two different food items and display the variations in their nutritional content. However, I'm encountering a couple of hurdles:

  1. Although the code is functioning properly, it returns NaN values and sometimes calculates as 0 when the quantity is increased.
  2. The current code only utilizes the first textbox for linking values, so changing values in the second textbox doesn't affect anything. Additionally, I'm struggling to figure out how to compute the difference between the units in the first textbox and those in the other textbox. Do I need to create another function for the second food item?

Here's the code I currently have:

var stocks = [
// Nutritional data goes here
];
  
function Stock (data) {
  // Function logic
}

stocks = stocks.map(Stock)

var $selects = $('.selectStock')
var $quantity = $('#numberOfStocks')
var $comparisonResult = $('.comparison .result')

// Remaining JavaScript code
  .side {
  // CSS styles for side div
}
.sideone {
  // CSS styles for sideone div
}
.mid {
  // CSS styles for mid div
}
.comparison {
  // CSS styles for comparison div
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<head>
  <meta name="viewport" content="width=10px, initial-scale=1.0">
</head>

<body>
  <label>
    <div class = "side">
    Amount:
    <input type="number" id="numberOfStocks" value="1" min="0" />
    </div>
    <br>
    <br>
    <br>
    <br>
  </label>

  <div>
    <div class="sideone">
      <h2>First Item<span class="servingUnit"></span>:</h2>
      <select class="selectStock">
        <option value="-1">Pick a food!</option>
      </select>
    </div>
    <label>
    <div class = "side">
      Amount:
    <input type="number" id="numberOfStocks" value="1" min="0" />
    </div>
    <br>
    <br>
    <br>
    <br>
  </label>
    <div class="sideone">
      <h2>Second Item<span class="servingUnit"></span>:</h2>
      <select class="selectStock">
        <option value="-1">Pick a food!</option>
      </select>
      <br>
      <br>
    </div>
    <div class="comparison side">
      <h2>Comparison:</h2>
      <br>
      <br>
      <div class="result"></div>
    </div>
  </div>
</body>

Your help and guidance on this matter are greatly appreciated. Thank you!

Answer №1

Take a look at this plunk: https://plnkr.co/edit/AwaiAKQYJHlbvzvRYDqi

Being Transparent

  • I made minimal changes to your code, focusing on fixing the specified issues only.
  • If I may add, without delving too deeply into the code structure.
  • If there were any calculation issues, I refrained from altering or analyzing them.

The solutions to your queries:

  1. I included a function to eliminate commas from formatted numbers used in calculations

    float parseToFloatWithoutCommas(str)
    .

  2. I converted the two textboxes' ID's to class, following your approach with the select boxes, as using the same ID multiple times in HTML is invalid, but it works fine with class :)

Enjoy ;-)

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

Is there a way to script the action of unchecking checkbox 1 when checkbox 2 is checked, and unchecking checkbox 2 when checkbox 1 is checked?

Is it possible to create a custom radio button behavior with two checkboxes? For example, if checkbox 1 is checked, can we automatically uncheck checkbox 2 and vice versa? ( Transforming checkboxes into radio buttons. ) <input type="checkbox" id="chec ...

Executing a nested function before moving on to the subsequent code statements

I have a requirement where certain functions in my codebase need to check if a user is logged in before proceeding. Instead of duplicating this check logic, I want to call a single getUser() function each time. Here is the order of operations for the func ...

Ways to include text beneath an image within a column using Bootstrap HTML code

Currently I am working on creating a box using Bootstrap, see the code below: <link rel="stylesheet" type="text/css" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css"> <style> .addonscard { width: 100%; ...

What is causing the extra whitespace on the right side with container-fluid?

Could someone assist me with an issue I'm experiencing when using the container-fluid in Bootstrap? It seems to be leaving some space on the right side of my web page, and as a newcomer to Bootstrap, any help would be greatly appreciated. <link ...

Show the array in the input field as an array

Check out my Plunker demo at the following link: https://plnkr.co/edit/stKf1C5UnCKSbMp1Tyne?p=preview angular.module('listExample', []) .controller('ExampleController', ['$scope', function($scope) { $scope.names = [&ap ...

Exploring the connections between React components and JSON schema forms

When the user selects an option from the dropdown in step 1 and submits, they will be redirected to either step2schema or step3schema based on their selection. Here is the link to the jsfiddle for reference: const Form = JSONSchemaForm.default; const st ...

Having trouble inserting an item into the localStorage array

In my localStorage, I store a list of movies that users have purchased tickets for using an array. However, I am encountering an issue where I cannot add new values to this array in the localStorage. Here is the code snippet: if(window.localStorage){ ...

Is there a way to use getJSON to append divs and animate them one by one as they are displayed?

Hey everyone! I'm currently using a getJSON function to append some divs, but I want to make the display more dynamic. Is it possible for each div to appear milliseconds apart? For example, the first div fades in, followed by the second, and so on. H ...

Transcluding content inside a table cell with Angular

Recently, I came across a peculiar issue with an attribute directive in Angular. This directive simply adds a class name to the element where it is applied, specifically to a table cell <td>. Oddly enough, when I set transclude: true in the directive ...

The behavior of the CSS Position property is exhibiting unique characteristics when used in

I am encountering an issue where an image is displaying differently based on the position attribute in Firefox compared to Chrome and IE11. Take a look at the preview on . Notice how the bottom tip of "Fountain Valley" is incorrectly positioned in Firefox ...

Exploring and locating React components within an array using map search

Hello everyone, I'm currently working with a table in my database that looks like this: st_ID firstName LastName Classes 1 paul adams php 1 paul adams javascript 1 paul adams ASP ...

Can React components be saved in an array?

I am currently working on enhancing the code snippet provided below. This code is intended to iterate through elements of an array using keys to locate images within a lengthy SVG file directly embedded in the document under the identifier "SomelongUglySVG ...

Exiting a chain of promises prematurely based on a condition without causing an error

Currently, I am facing a challenge in my node.js application. The issue lies within the registration route where I need to execute several asynchronous steps. At an early stage, there's a specific condition that requires me to halt the process and ret ...

How can I pull all data from an array using MongoDB query?

I have multiple arrays, but I am only interested in extracting the content related to "PIZZAS." Can anyone advise me on the appropriate query to achieve this? https://i.stack.imgur.com/wHolE.png ...

executing a "background process" in javascript

Can JavaScript execute functions in the background? I am using the pdfmake tool to generate a PDF within an AngularJS application, but the generation process takes around 3-4 seconds and causes the UI to freeze completely. I want to run a background task ...

How can I troubleshoot a C# web method called from an AJAX request in

I have a asp.net (web forms) c# code behind page that contains a web method which I trigger through an ajax call on the same page. Upon making the ajax POST call, I encounter a generic "Internal server error has occurred" message. To troubleshoot this is ...

Troubles with submitting forms in jQuery

I am facing an issue with submitting a form within fancybox (www.fancybox.net). When I directly access the form, it submits successfully. However, if I load the form within the page where I want to trigger fancybox from, the form does not submit and fancyb ...

Tips for displaying an element for each item chosen in a multi-select box

I currently have a situation where I am rendering for every selected element within my multiselect angular material selectbox. The rendering process functions correctly when I select an element, but the issue arises when I try to deselect one - it just ke ...

Investigating the issue of drag and drop functionality not working with the combination of rspec, capy

I am currently using the following tools and technologies: RSpec Capybara Selenium jQuery UI-Sortable Ruby Rails The following code snippet is being used: expect(find_by_id("note0").text).to eq(note_placeholder.to_s + "0") expect(find_by_id(" ...

Entering credit card information in a modal popup using Bootstrap form

I have implemented a bootstrap modal for my credit card payment form and now I want to validate the credit card information. Currently, I am using basic validation in jQuery. <script> $(function() { $('#error_message_reg').text(""); //$( " ...