The conditional statement within the EventListener does not seem to be functioning as intended

I am attempting to calculate BMI and then display additional information on the calculation result when a button is clicked. The 'what does this mean' button should show information based on the calculated BMI score.

const generatebutton = document.getElementById("explainbutton");


const wt = document.getElementById("b2");
const ht = document.getElementById("b3");
const bmi = document.getElementById("b5");
const calc = document.getElementById("b7");
const clr = document.getElementById("b8");

// // BMI calculation function
function calculate() {
  const wt = document.getElementById("b2").value;
  const ht = document.getElementById("b3").value;
  const solve = Number.parseFloat(wt / ht ** 2).toFixed(2);
  document.getElementById("b5").textContent = solve;
};

// Function to make 'explain' button visible
function genbutton() {
  generatebutton.style.visibility = "visible";
};


calc.addEventListener("click", function() {
  calculate();
  genbutton();
});

clr.addEventListener("click", function() {
  wt.value = "";
  ht.value = "";
  bmi.textContent = "";
});


// Set variables for explanation
const explain = document.getElementById("explain")

const under = document.getElementById("under")

const healthy = document.getElementById("healthy")

const over = document.getElementById("over")

const obese = document.getElementById("obese")

// Pop-up text
var btn = document.getElementById("explainbutton");
btn.addEventListener("click", function() {
  const bmi = document.getElementById("b5");
  if (bmi < 18.5) {
    explain.classList.toggle("open-under")
  } else if (bmi >= 18.5 && bmi < 24.9) {
    explain.classList.toggle("open-healthy")
  } else if (bmi > 24.9 && bmi < 29.9) {
    explain.classList.toggle("open-overweight")
  } else {
    explain.classList.toggle("open-obese")
  }
});
#explainbutton {
  visibility: hidden;
  margin-left: 190px;
}


/* Pop-up explanation options */

.box {
  background: white;
  visibility: hidden;
  margin: 20px auto;
  -webkit-transition: all 0.3s ease-in-out;
  -moz-transition: all 0.3s ease-in-out;
  -o-transition: all 0.3s ease-in-out;
  transition: all 0.3s ease-in-out;
}

.open-under .under {
  visibility: visible;
  width: 300px;
  height: 100px;
  -webkit-transition: all 0.3s ease-in-out;
  -moz-transition: all 0.3s ease-in-out;
  -o-transition: all 0.3s ease-in-out;
  transition: all 0.3s ease-in-out;
}

.open-healthy .healthy {
  visibility: visible;
  width: 300px;
  height: 100px;
  -webkit-transition: all 0.3s ease-in-out;
  -moz-transition: all 0.3s ease-in-out;
  -o-transition: all 0.3s ease-in-out;
  transition: all 0.3s ease-in-out;
}

.open-over .over {
  visibility: visible;
  width: 300px;
  height: 100px;
  -webkit-transition: all 0.3s ease-in-out;
  -moz-transition: all 0.3s ease-in-out;
  -o-transition: all 0.3s ease-in-out;
  transition: all 0.3s ease-in-out;
}

.open-obese .obese {
  visibility: visible;
  width: 300px;
  height: 100px;
  -webkit-transition: all 0.3s ease-in-out;
  -moz-transition: all 0.3s ease-in-out;
  -o-transition: all 0.3s ease-in-out;
  transition: all 0.3s ease-in-out;
}


/*  */
<div id="b1">
  <span id="sp1">
    WEIGHT(kg) :
  </span>
  <input type="number" id="b2">
  </input>
</div>
<br>
<div id="b9">
  <span id="sp2">
    HEIGHT(m) :
  </span>
  <input type="number" id="b3">
  </input>
</div>
<br>

<div id="bmibox">
  BMI :
  <span id="b5"> </span>
  <INPUT TYPE="BUTTON" VALUE="What does this mean?" class="styled-button-2" id="explainbutton" />
  <div class="box" id="explain">
    <span class="under" , id="under">You are in the underweight range</span>
    <span class="healthy" id="healthy"> You are in the healthy range </span>
    <span class="over" id="over"> You are in the overweight range </span>
    <span class="obese" id="obese"> You are in the obese range</span>
  </div>


</div>

<br>
<br>
<div id="b6">
  <INPUT TYPE="BUTTON" VALUE="Calculate" class="styled-button-2" id="b7" />
  <button id="b8">Clear</button>
</div>

The functionality of the pop-up works correctly without the conditional statement.

Therefore, I am unsure of the reason why the script is not executing. I have attempted isolating the conditional as a separate function before reintegrating it into the EventListener.

Answer №1

After realizing that the variable bmi in the event listener was capturing the entire text instead of just the number, I decided to use parseFloat() to convert the text to a number. This adjustment allowed the variable to store the correct numerical value. Additionally, I implemented a text variable to ensure that whenever the calculation was repeated, the previous result would be cleared and a new one displayed.

const generatebutton = document.getElementById("explainbutton");


const wt = document.getElementById("b2");
const ht = document.getElementById("b3");
const bmi = document.getElementById("b5");
const calc = document.getElementById("b7");
const clr = document.getElementById("b8");

// // calculate bmi funtion
function calculate() {
  const wt = document.getElementById("b2").value;
  const ht = document.getElementById("b3").value;
  const solve = Number.parseFloat(wt / ht ** 2).toFixed(2);
  document.getElementById("b5").textContent = solve;
};

// function make explain button appear 

function genbutton() {
  generatebutton.style.visibility = "visible";
};


calc.addEventListener("click", function() {
  calculate();
  genbutton();
});

clr.addEventListener("click", function() {
  wt.value = "";
  ht.value = "";
  bmi.textContent = "";
});


//set variables for explanation
const explain = document.getElementById("explain")

const under = document.getElementById("under")

const healthy = document.getElementById("healthy")

const over = document.getElementById("over")

const obese = document.getElementById("obese")

//pop up text
var text = '';
var btn = document.getElementById("explainbutton");
btn.addEventListener("click", function() {
  const bmi = parseFloat(document.getElementById("b5").textContent);
  if (text != ''){
    explain.classList.toggle(text)
  }
  if (bmi < 18.5) {
    text = "open-under"
    
  } else if (bmi >= 18.5 && bmi < 24.9) {
    text = "open-healthy"
  } else if (bmi > 24.9 && bmi < 29.9) {
    text = "open-over"
  } else {
    text = "open-obese"
    
  }
  explain.classList.toggle(text)
});
#explainbutton {
  visibility: hidden;
  margin-left: 190px;
}


/* pop-up explanation options */

.box {
  background: white;
  visibility: hidden;
  margin: 20px auto;
  -webkit-transition: all 0.3s ease-in-out;
  -moz-transition: all 0.3s ease-in-out;
  -o-transition: all 0.3s ease-in-out;
  transition: all 0.3s ease-in-out;
}

.open-under .under {
  visibility: visible;
  width: 300px;
  height: 100px;
  -webkit-transition: all 0.3s ease-in-out;
  -moz-transition: all 0.3s ease-in-out;
  -o-transition: all 0.3s ease-in-out;
  transition: all 0.3s ease-in-out;
}

.open-healthy .healthy {
  visibility: visible;
  width: 300px;
  height: 100px;
  -webkit-transition: all 0.3s ease-in-out;
  -moz-transition: all 0.3s ease-in-out;
  -o-transition: all 0.3s ease-in-out;
  transition: all 0.3s ease-in-out;
}

.open-over .over {
  visibility: visible;
  width: 300px;
  height: 100px;
  -webkit-transition: all 0.3s ease-in-out;
  -moz-transition: all 0.3s ease-in-out;
  -o-transition: all 0.3s ease-in-out;
  transition: all 0.3s ease-in-out;
}

.open-obese .obese {
  visibility: visible;
  width: 300px;
  height: 100px;
  -webkit-transition: all 0.3s ease-in-out;
  -moz-transition: all 0.3s ease-in-out;
  -o-transition: all 0.3s ease-in-out;
  transition: all 0.3s ease-in-out;
}


/*  */
<div id="b1">
  <span id="sp1">
    WEIGHT(kg) :
  </span>
  <input type="number" id="b2">
  </input>
</div>
<br>
<div id="b9">
  <span id="sp2">
    HEIGHT(m) :
  </span>
  <input type="number" id="b3">
  </input>
</div>
<br>

<div id="bmibox">
  BMI :
  <span id="b5"> </span>
  <INPUT TYPE="BUTTON" VALUE="What does this mean?" class="styled-button-2" id="explainbutton" />
  <div class="box" id="explain">
    <span class="under" id="under">You are in the underweight range</span>
    <span class="healthy" id="healthy"> You are in the healthy range </span>
    <span class="over" id="over"> You are in the overweight range </span>
    <span class="obese" id="obese"> You are in the obese range</span>
  </div>


</div>

<br>
<br>
<div id="b6">
  <INPUT TYPE="BUTTON" VALUE="Calculate" class="styled-button-2" id="b7" />
  <button id="b8">Clear</button>
</div>

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

Tips for creating a background image that seamlessly adjusts to various computer screen sizes

I am trying to make sure that an image fills the entire browser window, but unfortunately it has fixed width and height dimensions. Is there a way to adjust this so it displays correctly on screens of different sizes? Can CSS be used to stretch the backg ...

If I were to make 3 duplicate GET Ajax calls, would the browser wait for all three responses or process them individually?

If I were to make 3 identical calls in quick succession (within milliseconds), would the browser wait for one response or initiate 3 separate GET Ajax calls? Would it simply assign the response of one call to all 3, or is there a way to force it to do so ...

What is the best way to replace a CSS Background that is already marked as important?

Attempting to change the background of a website using Stylish, but encountering issues. The existing background css on the website includes an !important rule which is preventing Stylish from taking effect. Here is my code: body { background-image: n ...

The typeof operator is not functioning as anticipated when used with an ajax response

Trying to implement form validation using AJAX and PHP, but encountering issues with the typeof operator. The validation works smoothly except when receiving an empty response, indicating that all fields have passed. In this scenario, the last input retai ...

Informing the parent window of the child window's activities in order to adjust the timer for the user timeout feature

Within my Jquery function, I have implemented a feature that darkens the screen after a period of user inactivity. This triggers a pop-up window giving the user the option to stay logged in by clicking a button. If there is no response within the set time ...

What exactly is the function of the NextPage feature in Next.js?

Recently, I began incorporating TypeScript into my Next project. Could someone clarify the purpose of the following code snippets for me? import { NextPage } from 'next'; export const Page: NextPage = () => {} After reviewing the documentation ...

You should be providing a string value as expected. It seems that you may have overlooked exporting your component from the correct file it was defined in, or perhaps there is confusion with default and named

I encountered a strange error despite meticulously organizing and exporting/importing files. The code is structured from components to the App render method. Item.js import React from 'react'; import './Global.css' const Item = ({data ...

The Firebase signInWithPopup functionality suddenly shuts down in a Next.js project

Incorporating the signInWithPopup function for signing in has been successful during the development stage on my local server. const firebaseAuth = getAuth(app); const provider = new GoogleAuthProvider(); const [{ user, cartShow, cartItems }, dispatc ...

Using environmental variables in Nuxt 3 outside of component setup scripts can be easily achieved by accessing the variables directly

I have stored different API URLs in my .env file, specifically for development and production environments. Here is how I access these URLs: const isProdEnv = process.env.NODE_ENV === 'production' const DEV_API_URL = "https://example-stage.h ...

Navigating within a React application - rendering JSX components based on URL parameters

As I work on developing a web-app with a chapter/lesson structure, I have been exploring ways to handle the organization of lessons without storing HTML or React code in my database. One idea I had was to save each lesson as a .jsx file within a folder str ...

How can data be passed from a directive to a controller in Angular?

I am currently working on implementing a directive pagination feature and I need to pass the current page number from the directive to a controller in order to run a specific function with this argument. However, I keep getting an 'undefined' err ...

What could be causing this error I'm receiving: instance versus prototype difference?

Can someone help me understand the difference between .prototype and regular instances in JavaScript? I am confused about why this code is not working and getting a type error: "undefined is not a function". I am experimenting with the Ninja() class and ...

Creating visuals from written content

I am attempting to transform Y[0] into an image rather than text. Currently, it is only displayed as a plain text link and not as an image. <html> <head> <script type="text/javascript"> function modifyContent(){ var rows=document.g ...

Performing Jasmine unit testing on a component that relies on data from a service, which itself retrieves data from another service within an Angular 2+ application

Attempting to implement unit testing for a service using httpmock has been challenging. The service in question utilizes a method to make http get calls, but I have encountered difficulties in writing the test cases. saveservice.service.ts -- file const ...

Calculate the date difference in Nuxt by leveraging the @nuxtjs/moment module

I'm a Nuxt newbie facing an issue with calculating the difference between two dates (user input date and current date). The code I am using works fine in most cases, but when the input date is '2020-03-31' or '2020-01-30', the cons ...

Switching the checkbox state by clicking a button in a React component

Is there a way to update checkbox values not just by clicking on the checkbox itself, but also when clicking on the entire button that contains both the input and span elements? const options = ["Option A", "Option B", "Option C"]; const [check ...

Leverage the power of dynamic PHP variables within your JavaScript code

I have an image database and a search form. I want to display the images on the next page using JavaScript with the OpenLayers library. Here is the PHP code I wrote: <?php mysql_connect('localhost','root',""); mysql_select_ ...

Understanding the Intrinsic Dimensions of Replaced Elements in CSS

I'm currently facing some challenges with the CSS Intrinsic & Extrinsic Sizing Module Level 3, specifically chapter 4.1 on Intrinsic Sizes. This section is proving to be quite difficult for me: When a block-level or inline-level replaced element h ...

ES6: utilizing properties and methods of a subclass that inherit from the superclass

While ES6 does not have abstract methods or properties, is it possible to access some methods or properties from the parent class in an inherited class? class ParentClass { constructor(){ ParentClass.checkChildPropertyAccessibility(); Pa ...

Prevent title flickering in Android using Ionic

I am attempting to create a tab content page using the "standard" method recommended by the ionic template example. However, I have noticed that when switching between tabs on Android, the view title flickers. This issue is not present on iOS or desktop b ...