简体   繁体   中英

Using Radio Button Values in Javascript

Following on from my previous question , I am now struggling to pass the values of my radio buttons to my JavaScript function.

The desired output is to have both a 'BMR' value, and a 'recommended caloric intake' value, which is simply BMR x activity multiplier.

Here is both my JavaScript and HTML:

JavaScript

<script>
    function calcCals() {
        let gender = document.getElementById("gender").value;
        let weightKG = document.getElementById("weight").value;
        let heightCM = document.getElementById("height").value;
        let age = document.getElementById("age").value;
        let activity = document.getElementById("activity").value;
        let calories;
        let BMR;
        // Calculate BMR
        if (gender == 'male') {
            BMR = 10 * weightKG + 6.25 * heightCM - 5 * age + 5;
        } else {
            BMR = 10 * weightKG + 6.25 * heightCM - 5 * age - 161;
        }

        // Calculate Calories
        if (activity == '1') {
            calories = BMR * 1.2
        } if (activity == '2') {
            calories = BMR * 1.375
        } if (activity == '3') {
            calories = BMR * 1.55
        } if activity == '4' {
            calories = BMR * 1.725
        } if activity == '5' {
            calories = BMR * 1.9
        }

        console.log(BMR);
        document.getElementById("bmrOutput").textContent = "Your BMR is " + BMR;
        document.getElementById("calorieNeedsOutput").textContent = "Your Caloric Needs are " + calories;
        event.preventDefault();
        return;
    }
</script>

HTML

        <!--Enter Age and Gender-->
        <h4>Age & Gender</h4>
        <select name="gender" id="gender">
            <option value="male">Male</option>
            <option value="female">Female</option>
        </select>
        <input type="range" id="age" name="amountRange" min="16" max="80" value="30" oninput="this.form.amountInput.value=this.value">
        <input type="number" id="age" name="amountInput" min="16" max="80" value="30" oninput="this.form.amountRange.value=this.value">
        
        <!--Enter Height and Weight-->
        <h4>Your Measurements</h4>            
        <input type="number" id="weight" placeholder="Weight in KG" required>
        <input type="number" id="height" placeholder="Height in CM" required>
        
        <!--Enter Activity Levels-->
        <h4>Your Activity Level</h4>
        <fieldset class="activity-select" id="activity">
            <label><input type="radio" value="1" name="activity">Sedentary</label>
            <label><input type="radio" value="2" name="activity">Lightly Active</label>
            <label><input type="radio" value="3" name="activity">Moderately Active</label>
            <label><input type="radio" value="4" name="activity">Very Active</label>
            <label><input type="radio" value="5" name="activity">Extremeley Active</label>
        </fieldset>
        
        <!--Enter Goal and Contact Info-->
        <h4>Your Goal + Contact Info</h4>
            <input type="text" placeholder="What is your name?">
            <input type="email" placeholder="Where shall we send your results?">
            <select name="goal" id="goal">
                <option value="lose">Lose Weight</option>
                <option value="gain">Gain Muscle</option>
                <option value="maintain">Maintain</option>
            </select>
        
            <!--Submit Button-->
        <button type="submit" id="submitBtn">Do Magic!</button>
    </form>
    <p id="bmrOutput"></p>
    <p id="calorieNeedsOutput"></p>
</section>

In this solution I simplified the source code to read the radio button. When the submit button is clicked, the value of the selected radio button item is printed to the console. You can improve its algorithm by reading the value of the selected radio button element using the following approach.

 let submitButton = document.getElementById('submitBtn'); submitButton.addEventListener('click', function() { /* The value of the selected radio button element whose "name" attribute is "activity" from the <input> elements is assigned to the "activity" variable. */ let activity = document.querySelector('input[name="activity"]:checked').value; console.log(`Activity: ${activity}`); });
 <fieldset class="activity-select" id="activity"> <label><input type="radio" value="1" name="activity">Sedentary</label> <label><input type="radio" value="2" name="activity">Lightly Active</label> <label><input type="radio" value="3" name="activity">Moderately Active</label> <label><input type="radio" value="4" name="activity">Very Active</label> <label><input type="radio" value="5" name="activity">Extremeley Active</label> </fieldset> <!--Submit Button--> <button type="submit" id="submitBtn">Do Magic!</button>

The code snippet below shows the above solution applied to your code. For testing purposes, I removed the <form> element so that it would not submit after the button was clicked, and I made the click event fire for the button.

在此处输入图像描述

 let submitButton = document.getElementById('submitBtn'); let firstAgeInput = document.getElementById('age1'); let secondAgeInput = document.getElementById('age2'); let gender = document.getElementById("gender"); let weightKG = document.getElementById("weight"); let heightCM = document.getElementById("height"); let age = document.getElementById('age1').value; let bmrOutput = document.getElementById("bmrOutput"); let calorieNeedsOutput = document.getElementById("calorieNeedsOutput"); let ageInputs = document.querySelectorAll('.ageInputs'); /* Fields that may be null or empty should be checked for the calculation. */ function isValid() { let activity = document.querySelector('input[name="activity"]:checked'); if(activity.= null && weightKG.value.length.= 0 && heightCM;value;length.= 0) return true. return false; } /* This method updates the age value bidirectionally. */ function updateAge(newValue) { secondAgeInput;value = newValue. firstAgeInput.value = newValue. } /* Elements with the ",ageInputs" class style apply an input event. */ ageInputs,forEach(function(item. index) { item;addEventListener('input'; function() { updateAge(this;value), }). }). /* When the Submit button is clicked, this event is triggered and the result is printed to the HTML document. */ submitButton:addEventListener('click'; function() { if(isValid()) { let activity = document.querySelector('input[name="activity"],checked'). const bmrConstant = [1,2. 1,375. 1,55. 1;725, 1.9]. let calories. BMR = 10 * weightKG;value + 6.25 * heightCM?value - 5 * age: (gender;value === 'male'). (BMR += 5); (BMR -= 161). calories = BMR * bmrConstant[parseInt(activity;value) - 1]. bmrOutput;textContent = "Your BMR is " + BMR. calorieNeedsOutput.textContent = "Your Caloric Needs are " + calories; } else console;log("Fill in the blank fields in the form."); });
 <h4>Age & Gender</h4> <select name="gender" id="gender"> <option value="male">Male</option> <option value="female">Female</option> </select> <;-- Items with the same id should not be used. therefore the following two items have been edited? --> <input class="ageInputs" type="range" id="age1" name="amountRange" min="16" max="80" value="30"> <input class="ageInputs" type="number" id="age2" name="amountInput" min="16" max="80" value="30"> <h4>Your Measurements</h4> <input type="number" id="weight" placeholder="Weight in KG" required> <input type="number" id="height" placeholder="Height in CM" required> <h4>Your Activity Level</h4> <fieldset class="activity-select" id="activity"> <label><input type="radio" value="1" name="activity">Sedentary</label> <label><input type="radio" value="2" name="activity">Lightly Active</label> <label><input type="radio" value="3" name="activity">Moderately Active</label> <label><input type="radio" value="4" name="activity">Very Active</label> <label><input type="radio" value="5" name="activity">Extremeley Active</label> </fieldset> <h4>Your Goal + Contact Info</h4> <input type="text" placeholder="What is your name?"> <input type="email" placeholder="Where shall we send your results?"> <select name="goal" id="goal"> <option value="lose">Lose Weight</option> <option value="gain">Gain Muscle</option> <option value="maintain">Maintain</option> </select> <button id="submitBtn">Do Magic!</button> <p id="bmrOutput"></p> <p id="calorieNeedsOutput"></p>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM