Trouble with using .className for form validation

The .className is not applying the formValidation class on getWeight.length < 1 and getHeight.length < 1. I am stuck trying to figure out why this is happening after reviewing the code extensively.

Any thoughts on what could be causing this issue? Your insights would be greatly appreciated!

Thank you, JS

function calculateBMI() {

  let getWeight = document.getElementById('weight').value;
  let getHeight = document.getElementById('height').value;
  let getBMI = (getWeight / (getHeight*getHeight)).toFixed(2);
  let displayBMI = document.getElementById('displaybmi');

  if (getWeight.length < 1) {
     //alert('Please enter your weight');
      getWeight.className = 'formValidation';
    }
  else if (getHeight.length < 1) {
     //alert('Please enter your height');
     getHeight.className = 'formValidation';
    }
  else if(getBMI < 18.5) {
    displayBMI.className = 'displaybmi green';
    displayBMI.textContent = 'You\'re under weight! ' + getBMI;
    } 

   else if (getBMI >= 18.5 && getBMI <= 25) {
    displayBMI.className = 'displaybmi green';
    displayBMI.textContent = 'You\'re normal weight! ' + getBMI;
    }

   else if (getBMI > 25 && getBMI <= 29.99) {
    displayBMI.className = 'displaybmi yellow';
    displayBMI.textContent = 'You\'re over weight! ' + getBMI;
    }

   else if (getBMI >= 30 && getBMI <= 34.99) {
    displayBMI.className = 'displaybmi orange';
    displayBMI.textContent = 'You\'re obese! ' + getBMI;
    }

   else {
    displayBMI.className = 'displaybmi red';
    displayBMI.textContent = 'You\'re very obese! ' + getBMI;
   } 

}
.displaybmi {
  font-size: 16px;
  padding: 20px;
  margin-bottom:20px;
}

.red{
  background:red;
}

.yellow {
  background: yellow;
}

.green{
  background:green;
}

.orange {
  background:orange;
}

.formValidation {
  border: 2px solid red;
}

Answer №1

When attempting to assign a classname to an element's value (such as an input), keep in mind that getWeight and getHeight represent values, not the actual DOM elements themselves.

Consider updating your code to:

let getWeight = document.getElementById('weight');
let getHeight = document.getElementById('height');
let getBMI = (getWeight.value / (getHeight.value*getHeight.value)).toFixed(2);

if (getWeight.value.length < 1) {
    //alert('Please enter your weight');
    getWeight.className = 'formValidation';
}
else if (getHeight.value.length < 1) {
    //alert('Please enter your height');
    getHeight.className = 'formValidation';
}

For more examples, visit this CodePen link.

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

Having trouble with a single GET request not functioning properly on Safari due to an Authorization issue in Angular 6

I've encountered this issue in several locations, yet haven't found a clear solution. Only one GET request is showing as unauthorized (401), but when I check the debugger, everything seems to be fine and all other requests are functioning properl ...

Enhance your textbox with more detailed descriptions than just displaying NaN

I am working on a form that includes select boxes. If a user selects an option from "Convert From" and another option from "Convert To" but does not enter a number in the input field, instead of displaying NaN in the result text box, I would like to show ...

Ways to Export HTML to Document without any borders or colorful text

How can I make a contentEditable area visible when filling text and then disappear when exporting the document? I found a script online that allows you to do this, but the issue is that the contentEditable area is not visible until clicked on. To address t ...

Exploring the possibilities of integrating JSONP with Framework7

I've been attempting to retrieve images from the Instagram public API using ajax and JSONP: var target = https://www.instagram.com/p/BP3Wu_EDXsjdT5Llz13jFv2UeS0Vw0OTxrztmo0/?__a=1?callback=?'; $$.ajax({ ty ...

Switch the menu state to closed when we click outside of it while it's open

I'm currently working on a scenario involving a menu that toggles when a button is clicked. The issue I'm facing is that when I click on the menu button, it opens correctly. However, the problem arises with the following code: Whenever I click ...

Tips for transferring a list via ajax to a controller

Having a controller as follows.. public ActionResult Report(List<string> invoiceIds) and utilizing an ajax call like this... function generateAccountsPayableReports() { var ms = $("#msInvoicesAPV").data("kendoMultiSelect"); var invoices = ...

Merge the data from various sections of a JSON object into a unified array

Upon completing an ajax call to a specific URL, I receive data in the form of a JSON object structured like this: {"field1":["val1","val2","val3",...,"valn"], "field2":["vala","valb","valc",...,"valx"]} My goal is to merge the values of field1 and field ...

What is the process for connecting personalized toggle controls to a checkbox input field?

I have created a custom slide toggle control to enhance the functionality of my checkboxes in the app. You can check out the controls by following this link: http://codepen.io/spstratis/pen/fJvoH Currently, I am looking for a way to connect these switche ...

Harnessing the power of JSON within an HTML document to display dynamic data

Check out the JSON data through this link: The JSON file contains information about the weather. I need assistance with incorporating the data from the provided link into my HTML document as I am new to utilizing JSON for this purpose. <html> < ...

My goal is to implement a confirmation modal prior to any route changes within Next.js framework

Below is the code block that I have: const onRouteChangeStart = React.useCallback(() => { if (formState.isDirty) { if (window.confirm('Confirmation message')) { return true; } NProgress.done(); throw "A ...

Error: The hook call is invalid and can only be made within the body of a function component in ReactJS

Hello everyone, I am currently facing an issue with saving the lat and lng variables in the state within a hook. When trying to do so, I encounter the following error message: "Error: Invalid hook call. Hooks can only be called inside the body of a functio ...

Transform date format using VueJS in JavaScript

I need to convert a date format from 19 Oct 2017 to 20171019. Is there a way to do this quickly? I am using FlatPickr in VueJs. Here is the code snippet for reference: import flatPickr from 'vue-flatpickr-component'; import 'flatpickr/dist/ ...

Is there a way to prevent the use of angular.reloadWithDebugInfo() in the browser console?

Is there a way to secure app scope variables from being accessed through the browser console? I've already disabled debug info using $compileProvider.debugInfoEnabled(false); But it seems like this setting can still be bypassed with reloadWithDebugIn ...

Using Golang to encode JSON for parsing in JavaScript

I am working with a struct that looks like this: type User struct { Login string `json:",string"` PasswordNonce Nonce `json:",string"` PasswordHash HashValue `json:",string"` CreatedOn time.Time `json:",string"` Email ...

Creating a CSS full-width navigation menu

Recently, I came across a menu code on the web that seemed great. However, I wanted to make my menu responsive and full width. Since I am new to CSS and HTML, adjusting the menu code has been a bit of a challenge for me. .menu, .menu ul { list-style: ...

Introducing Vuetify 3's v-file-input with interactive clickable chips!

I noticed an unexpected issue with the v-file-input component in Vuetify3. In Vuetify 2, it was possible to use the selection slot to customize the display of selected files. This functionality still works in both versions, as mentioned in the documentatio ...

Creating a Cross Fade Animation effect with the combination of CSS and JavaScript

I've been attempting to create a similar animation using html and css. Below gif shows the desired outcome I am aiming for: https://i.sstatic.net/YsNGy.gif Although I have tried the following code, I have not been able to achieve the desired result ...

Effect on Label in WordPress Contact Form 7 When Input Field is Populated

Currently, I am attempting to achieve the floating label effect on Contact Form 7 and have encountered an issue. Although I have successfully implemented the label effect on input:focus, I am struggling to make it persist once text has been entered and foc ...

Error loading code. Works when manually pasted, but not when executed with JavaScript

After some trial and error, I found that this code works perfectly if I manually copy the content from the class isotope in 1.php to the class grid on this page. However, when I try to use JS to do the same thing, it mysteriously stops working. Any sugge ...

What is the process of connecting two models in Mongoose?

In this scenario, we have two models - ProductModel and CategoryModel. The goal here is to establish a connection between creating a product (ProductModel) and assigning it to a category. The issue arises when the category field is not getting filled in t ...