What is the solution to determining the accurate span form value?

The script below calculates a simple sum, displaying an error if the sum exceeds or falls below 100. Despite the error message, the user can still proceed to the next page. I want to restrict the user from moving to the next page until the sum equals 100.

<table class="table-bordered" style=" width: 80%; margin-left: 10%;" >
  <tr style="background-color:#ffb380">
        <td scope="col"  colspan="1" style="text-align:center"> Quante Palline  per la Scelta 1 </td>
        <td scope="col"  colspan="1" style="text-align:center"> Quanti Palline per la Scelta 2 </td>
        <td scope="col"  colspan="1" style="text-align:center"> Totale Palline Assegnate </td>
  </tr>
  <tr style="background-color:#ffe0cc">
        <td> <input class="pref_input" id="pref1" type="number" name="pref1" min="0" max="100" style="width: 50%; margin-left: 25%"> </td>
        <td> <input class="pref_input" id="pref2" type="number" name="pref2" min="0" max="100" style="width: 50%; margin-left: 25%"> </td>
        <td> <span  id="sum_token"  style="width: 50%; margin-left: 37%" ></span> su 100</td>
    </tr>
</table>


<div id="error" class="hide"><b>La somma dei gettoni deve essere 100</b></div>
<script>window.onload = init_sum_token();

function init_sum_token() {
  sum_token = document.getElementById("sum_token");
  pref1 = document.getElementById("pref1");
  pref2 = document.getElementById("pref2");

  document.querySelectorAll(".pref_input").forEach((item) => {
    item.addEventListener("change", (event) => {
      sum_prefs =
        get_input_value(pref1) +
        get_input_value(pref2);
      let sum = parseFloat(sum_prefs);
      if (sum != 100) {
        sum = sum_prefs;
        document.getElementById("error").className = "show";
      } else {
        document.getElementById("error").className = "hide";
      }
      sum_token.innerHTML = sum;
    });
  });
}
function get_input_value(input) {
  if (input.value == "") {
    return 0;
  } else {
    return parseFloat(input.value);
  }
  if (input.value != 100) {
    return "error";
  }
}

</script>

Answer â„–1

When comparing the sum in the function get_input_value(), ensure it is done accurately:

if (input.value > 100 || input.value < 100 ) {
    return "error";
  }

Furthermore, make sure to correct this part as well:

if (sum > 100 || sum < 100) {
        sum = sum_prefs;
....

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

The seamless integration of CocoonJS and Three.js with webGLRenderTarget for a smooth and efficient

When using three v 67's WebGLRenderTarget to render a second camera/scene to a buffer for future use in a texture, everything works fine in Three.js, but unfortunately, it encounters issues in CocoonJS. Various attempts have been made to access the d ...

Selenium Python option other than using send_keys()

I was looking to enhance the efficiency of this Python code and found a faster alternative: driver.get(myUrl) message = driver.find_element_by_id('message') send = driver.find_element_by_id('submit') for _ in range(myRange): messa ...

JavaScript function to toggle the visibility of navigation with a click of a button

I'm attempting to create a functionality in my code where the Open navigation button hides when the side navigation opens upon clicking. The desired behavior is for the openNav button to be hidden when it's clicked and then shown again when close ...

The ion-nav-buttons controller is triggering twice

Seeking a solution for displaying badges based on need inside the ion-nav-buttons. However, facing an issue where the controller inside the ion-nav-buttons is triggered twice. Interestingly, placing it outside the ion-nav-buttons resolves this problem. Fo ...

Displaying the response from the render function inside a div using express

In my current project, I am utilizing nodejs with express and attempting to load an ejs file into a div element as shown below: app.js (server side) //SHOW app.get("/courses/:id", function(req,res){ console.log("requested"); res.render('cour ...

Is it possible to apply fog to a specific area in Three.js instead of being dependent on the distance from

Picture this: a vast THREE.PlaneGeometry representing the floor with a camera placed at an arbitrary spot within the scene. By manually adjusting the near and far values of the fog, I can effectively conceal the outer edges of the plane to create the illu ...

Solving issues with Angular4 Router changes

I'm attempting to chain the router resolver for my application. Below are my Router options: { path: '', component: AdminComponent, resolve: [ SessionResolve, LocaleResolve ] } The desired flow is to first call S ...

Executing an Ajax callback function to navigate to a different page

I must handle ajax errors globally by capturing 901 error codes in my header.jsp. There is an error message displayed in the browser console: GET https://localhost:8443/SSApp/Pan/report?&vessel…namax%20Tanker%20Pool%20Limited&rptTitle=Activit ...

How can I position images in the center evenly?

I am currently working on implementing a 3D image carousel. It seems to work fine with an odd number of images, but when I add an even number of images and the positions change, the alignment gets offset to the left instead of center. Here is the link to ...

Verify the requests in node.js with Wordpress authentication

I am working on building a web application that consists of both a Wordpress site and a node.js application. I specifically chose to use Node because of the capabilities of socket.io, while Wordpress serves my needs for many other reasons. It's essent ...

What is causing the image to become distorted on the canvas?

Despite specifying the image dimensions to be 50px by 50px, it appears stretched on the y-axis like this. View Stretched Image I suspect that the issue lies with the CSS styling applied. Here is my current CSS code: canvas { background-color: green; ...

Exploring a property within a JavaScript object

Within my code, I am working with an array of objects called user. When I try to log the first object using console.log(user[0]);, I receive this output: Object {activityId: "2", id: "1", activityDt: "01/15/2016"} Afterwards, I attempt to store user[0] in ...

turning every input field's border to red if none of them were filled out at least once

I struggle with javascript and need some help. I have a form with multiple input fields, and I want to ensure that the user fills in at least one of them. I found code that triggers an alert message if the user does not fill in any fields, but I would pref ...

Exploring the World of Unit Testing with Jasmine and Sinon Factories

At my factory, I have implemented a getter and setter function .factory('myService', function() { var car = null; return { car: car, get: function get() { return car; }, set: function set(newCar) { car = newCar; ...

Utilize jQuery to enclose nested elements within a parent element

There is a Markup presented below, where this HTML content is being generated from Joomla CMS. I am seeking a jQuery method to reorganize this HTML structure without modifying its PHP code. <div class="item column-1"> <div class="page-header"& ...

What are the drawbacks of making API calls in getStaticProps?

After looking through the nextJs documentation, I came across a recommendation not to make API calls within the getStaticProps function. Can someone provide a clear example explaining why this is advised? The reason given in the docs is that server-side ...

ERROR: JSON - Cannot access property of undefined

My goal is to extract JSON values and create variables from them, but I keep encountering an error. Even when the JSON array is filled, I still face issues. var tempArray = []; $("#sth td").each(function(){ $this = $(this); tempArray.push({"COLO ...

Visualize data retrieved from a third-party website through scraping in a chart

After attempting to extract data from a website's data.asp file (formatted in json) and display it as a chart on my site using Google Chart API or FusionCharts, I'm facing issues. Although I can retrieve the json data, it doesn't render as a ...

Tell apart the scrolling that users start themselves from the scrolling that is triggered by the browser when a page is first loaded

Can anyone help me figure out how to detect when a user first starts scrolling on my page, rather than the automatic browser-initiated scrolling that occurs on page reload? I've tried capturing the window's initial scroll position and using a ...

The Vuex this.$store is not defined in the "mounted" lifecycle hook of the component

Currently in the process of integrating Paypal into my Vue project, following the official documentation and copying the necessary code from here. Successfully rendered the Paypal button, completed the transaction, and obtained an orderID. However, encount ...