Looking for assistance with a Vue.js BMI Calculator project

Currently, I am delving into Web Development using Vue. As part of my project, I have constructed a component that calculates the BMI (Body Mass Index) of an individual. To collect the necessary data, I have implemented a form utilizing bootstrap-vue. However, I find myself in need of assistance with the JavaScript section of this task as I am uncertain about how to rectify it.

<template>
  <div class="bmi-calc">

      <b-card title="BMI Calculator" img-src="https://picsum.photos/600/300/?image=25" img-alt="Image" img-top tag="article" style="max-width: 20rem;" class="mb-2">

        <b-form @submit="onSubmit" v-if="show">
            <!-- Height -->
            <b-form-group id="input-group-height" label="height" label-for="input-height" description="Height in cm">
                <b-form-input id="input-height" v-model="form.height" type="height"></b-form-input>
            </b-form-group>
            <!-- Weight -->
            <b-form-group id="input-group-weight" label="weight" label-for="input-weight" description="Weight in kg">
                <b-form-input id="input-weight" v-model="form.weight" type="weight"></b-form-input>
            </b-form-group>
        </b-form>

        <b-button type="submit" variant="primary">Submit</b-button>
        <div>Solution is: <strong>{{ solution }}</strong></div>

        </b-card>
    </div>
</template>


<script>
export default {
  data () {
    return {
      form: {
        height: '',
        weight: ''
      },
      show: true
    }
  },
  methods: {
    onSubmit (evt) {
      evt.preventDefault()
      var solution = null
      solution = this.weight / (this.height) ^ 2
    },
    onReset (evt) {
      evt.preventDefault()
      // Reset our form values
      this.form.height = ''
      this.form.weight = ''
      // Trick to reset/clear native browser form validation state
      this.show = false
      this.$nextTick(() => {
        this.show = true
      })
    },
  }
}

</script> 

The formula utilized for calculation:

Answer №1

Here are a few issues that need attention:

  1. The Submit button should be placed inside the form to trigger a submit event correctly:
<b-form>
  <b-form-group>...</b-form-group>

  <b-button type="submit">Submit</b-button>
</b-form>
  1. The template references solution, which is only a local variable within onSubmit(). To make it available for rendering, initialize it as a prop in data() and set it later in onSubmit() using this.solution = /* new value */.
export default {
  data() {
    return {
      //...
      solution: 0,
    }
  }
}
  1. onSubmit() uses this.weight and this.height, but these values are actually stored under this.form, so they should be referenced as this.form.weight and this.form.height respectively.

  2. The BMI calculation does not use the correct syntax for squaring a number. You can either use Math.pow(), or multiply it by itself:

export default {
  methods: {
    onSubmit() {
      this.solution = this.form.weight / Math.pow(this.form.height, 2)
      // OR
      this.solution = this.form.weight / (this.form.height * this.form.height)
    }
  }
}
  1. The <b-form-input>s are bound to form.height and form.weight, but currently, these are strings instead of numbers, leading to errors in BMI calculation. The input types should be corrected to type="number". When using v-model with a number, ensure to utilize the .number modifier for updating the value to the proper type:
<b-form-input v-model.number="form.weight" type="number">
<b-form-input v-model.number="form.height" type="number">

https://codesandbox.io/s/binding-to-number-inputs-yhjzr?fontsize=14&hidenavigation=1&module=%2Fsrc%2Fcomponents%2FDemo.vue&theme=dark

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

Locating the elusive sequence number within a document

Greetings, I am currently trying to locate a missing number within an xml file but seem to be encountering some challenges. Any suggestions or ideas would be greatly appreciated. Example The file contains an <a> tag with various ids such as page-1, ...

What could be causing the issue with Collection.find() not functioning correctly on my Meteor client?

Despite ensuring the correct creation of my collection, publishing the data, subscribing to the right publication, and verifying that the data was appearing in the Mongo Shell, I encountered an issue where the following line of code failed to return any re ...

Various results can be produced based on the .load() and .resize() or .scroll() functions despite using the same calculation methods

I'm currently working on developing my own custom lightbox script, but I've hit a roadblock. For centering the wrapper div, I've utilized position: absolute and specified top / left positions by performing calculations... top: _center_ver ...

The jQuery method .on gathers and retains click events

I created a component that manages a view containing articles with games. In order to prevent memory overload and optimize performance, I implemented a solution where when a user clicks on an article (each having the class "flashgame"), they can choose to ...

Load the dropdown menu with JSON data but encounter an error: SyntaxError caused by an unexpected token `{` in

I am currently working on populating a dropdown menu with the values of the 'styleName' field from a JSON data file. Here is an example of my JSON data: {"name":{"styleName":"name","fillType":"none","fillTrans":"0","outlineType":"solid","outlin ...

Adjust the width of a container to exceed 32767 using jquery in the Opera browser

I am looking to create a compact timeline using jQuery, and I want this timeline to have a width exceeding 32767 pixels. Interestingly, when I attempt to modify the width using the jQuery code $(".timelinecontainer").width(32767);, it doesn't seem to ...

Scrolling to a specific position on a page when a Vue 3 component appears is a must-do for

When I click a button, my basic form component appears without using the router. I would like the scroll position of the form to automatically move down slightly (for example, on the y-axis at 40) once it is displayed. However, I am unsure of how to achi ...

Learn the steps to designing a responsive class using Angular2's ngClass feature

Imagine a scenario where the object models in my cloud Array include a weight key: return [ { term: '1994', weight: 0 }, { term: '2017', weight: 0 }, { term: '89th', ...

Checkbox ensemble computes total score

I am currently working on a project that involves multiple checkbox groups, with each group containing 3 checkboxes labeled as (1, X, 2). My goal is to assign a value of 100% to each group, distributed evenly among the checkboxes within it. The distributio ...

Please rewrite the following sentence: "I am going to the store to buy some groceries."

As I navigate through my styled HTML page, an interesting sequence of events unfolds. When the Create New List button is clicked, a pink div emerges, contrasting with the orange hue of the All Lists div. At this moment, a new user has joined but hasn' ...

What is the reason behind the state of a transition not being preserved once it has concluded?

I was interested in enhancing the basic transitions example by having an element fade out in one div while simultaneously fading in on another: new Vue({ el: '#demo', data: { show: true } }) .fade-enter-active, .fade-leave-active { ...

Use radio buttons to enable switching between different data options within a dropdown menu

I am working on a dropdown box that is populated dynamically using JSON data. The content in the dropdown can be categorized into 4 types, so I have included radio buttons to switch between these categories. I have created HTML code to toggle between manu ...

How can I arrange individual events in agendaWeek view on FullCalendar.io and then merge them all into one line?

I am using Fullcalendar.io version 2 When I switch to the agendaWeek mode, all my events are displayed on one line in each day square. As a result, the more events I have, the thinner the event blocks become. Is there a way for me to display only one eve ...

What is the reason for the failure of the jQuery code to disable the submit button in the following snippet?

I am working on a feature to disable the submit button in a form when the username, email, password fields are empty. When all of them are filled, I want to enable the submit button. However, the current code is not disabling the submit button as expected. ...

Delaying Variable Assignment in Node.js until Callback Function Completes

I am currently working with Node.js, Express, MongoDB, and Mongoose in my project. One specific task involves fetching the largest id number of a document from the MongoDB database and passing it back to the program. To better organize my code, I moved thi ...

Adjust the size of an element in response to changes in the size of

I've implemented a jQuery function to resize an element dynamically based on window size changes: $(window).resize(function() { topHeight = $("#top").height(); height = $(window).height() - 210; $("#container").height(height); $("#g").height( ...

Retrieving external JSON data with JavaScript

I am attempting to utilize a specific service for proxy checking. They offer an uncomplicated API that delivers JSON data. My goal is to retrieve this JSON on my own server. Despite various attempts, I consistently encounter either a CORS request issue or ...

ways to make a list element inaccessible by using either Javascript or jQuery

When the user clicks on my eraser, I want the color to be hidden or not display its dropdown elements. I attempted this with the following code snippet. $('#chooseEraser').mousedown(function(e){ curTool = "eraser"; checkEraser ...

Avoiding a jest compile error and executing the test efficiently

Here is my Vue.js code snippet: export default { name: 'App', components: { }, created() { let t = typeof t === 'undefined' ? {} : t; // ISSUE LINE } } The ISSUE LINE runs successfully in the browser without any errors an ...

Steps for loading a different local JavaScript file by clicking on a button

My goal is to reload the browser page and display a different ReactJS component/file when a button is pressed. Initially, I attempted using href="./code.js" or window.location="./code.js" within the button props, but unfortunately, it did not yield the des ...