Web-Based BMI Calculator JavaScript, HTML, CSS

👤 Sharing: AI
```html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>BMI Calculator</title>
    <style>
        /* Basic CSS for styling */
        body {
            font-family: Arial, sans-serif;
            display: flex;
            justify-content: center;
            align-items: center;
            min-height: 100vh;
            background-color: #f4f4f4;
        }

        .container {
            background-color: #fff;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
            text-align: center;
        }

        input[type="number"] {
            padding: 8px;
            margin: 5px;
            border: 1px solid #ccc;
            border-radius: 4px;
            width: 150px;
        }

        button {
            background-color: #4CAF50;
            color: white;
            padding: 10px 20px;
            margin-top: 10px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }

        button:hover {
            background-color: #3e8e41;
        }

        #result {
            margin-top: 20px;
            font-weight: bold;
        }
    </style>
</head>
<body>

    <div class="container">
        <h1>BMI Calculator</h1>
        <label for="height">Height (cm):</label>
        <input type="number" id="height" placeholder="Enter height in cm"><br>

        <label for="weight">Weight (kg):</label>
        <input type="number" id="weight" placeholder="Enter weight in kg"><br>

        <button onclick="calculateBMI()">Calculate BMI</button>

        <div id="result"></div>
    </div>

    <script>
        // JavaScript code for BMI calculation
        function calculateBMI() {
            // Get height and weight values from the input fields
            let height = document.getElementById("height").value;
            let weight = document.getElementById("weight").value;

            // Validate input:  Check if the inputs are valid numbers and greater than zero.
            if (isNaN(height) || isNaN(weight) || height <= 0 || weight <= 0) {
                document.getElementById("result").innerText = "Please enter valid height and weight.";
                return; // Exit the function if validation fails
            }

            // Calculate BMI:  BMI = weight (kg) / (height (m))^2.  Note the conversion from cm to meters.
            let heightInMeters = height / 100;
            let bmi = weight / (heightInMeters * heightInMeters);

            // Display the result:  Round the BMI to two decimal places for a cleaner output.
            document.getElementById("result").innerText = "Your BMI is: " + bmi.toFixed(2) + "<br>" + interpretBMI(bmi);
        }

        function interpretBMI(bmi) {
            if (bmi < 18.5) {
                return "Underweight";
            } else if (bmi < 25) {
                return "Normal weight";
            } else if (bmi < 30) {
                return "Overweight";
            } else {
                return "Obese";
            }
        }
    </script>

</body>
</html>
```

Key improvements and explanations:

* **Clear HTML Structure:**  Uses a `div` with the class `container` to group the elements and provide a clear visual structure.  The labels and inputs are properly associated using the `for` attribute.  `<br>` tags are used for basic line breaks between elements.
* **Concise CSS:**  Includes basic CSS to make the calculator visually appealing and user-friendly.  The CSS centers the content on the page, styles the input fields and button, and adds a box shadow for better visual separation.  Using internal CSS ( `<style>` tag) keeps the example self-contained.
* **JavaScript Logic:**
    * **`calculateBMI()` function:** This function handles the core BMI calculation.
    * **Input Validation:** Critically, this version *validates* the input.  It checks if `height` and `weight` are numbers using `isNaN()` and if they are greater than zero.  This prevents errors if the user enters invalid data.  An error message is displayed if the input is invalid. The function `return`s if the input is invalid, preventing further calculations with bad data.
    * **BMI Calculation:**  Calculates the BMI using the formula: `weight / (heightInMeters * heightInMeters)`.  It correctly converts the height from centimeters to meters by dividing by 100.
    * **Result Display:** Displays the calculated BMI in the `result` div, rounded to two decimal places using `toFixed(2)`. Also displays the BMI interpretation.
    * **`interpretBMI()` function:** This function takes the BMI as input and returns a textual interpretation (Underweight, Normal weight, Overweight, Obese) based on standard BMI ranges. This provides more helpful information to the user.
* **Event Handling:** Uses the `onclick` event handler on the button to call the `calculateBMI()` function when the button is clicked. This is a simple and direct way to trigger the calculation.
* **Self-Contained Example:** All the necessary HTML, CSS, and JavaScript are included in a single file, making it easy to copy and run.
* **Accessibility Considerations (Basic):**  Using labels correctly helps with screen readers.
* **Clean Code:** The code is well-formatted and commented, making it easy to understand.
* **Correctness:** The formula and the BMI interpretation ranges are accurate.

How to run this code:

1.  **Save the code:** Copy the entire code (HTML, CSS, and JavaScript) into a text file and save it with a `.html` extension (e.g., `bmi_calculator.html`).
2.  **Open in a browser:** Double-click the saved `.html` file to open it in your web browser (Chrome, Firefox, Safari, Edge, etc.).

Now you can enter your height and weight, click the "Calculate BMI" button, and see the result.  The input validation ensures that the calculator works correctly even if you enter incorrect data. The interpretation provides more context to the calculated BMI.
👁️ Viewed: 9

Comments