简体   繁体   English

在 Javascript 中使用单选按钮值

[英]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.继上一个问题之后,我现在正在努力将单选按钮的值传递给我的 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.所需的 output 将同时具有“BMR”值和“推荐热量摄入”值,即 BMR x 活动乘数。

Here is both my JavaScript and HTML:这是我的 JavaScript 和 HTML:

JavaScript 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 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.出于测试目的,我删除了<form>元素,以便在单击按钮后它不会提交,并且我为按钮触发了单击事件。

在此处输入图像描述

 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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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