简体   繁体   English

我需要使用DOM计算一些选中的单选按钮的值

[英]I need to calculate the value of some checked radio buttons using DOM

My code so far is: HTML 到目前为止,我的代码是:HTML

<input type="radio" name="age" value="0">1-25
<input type="radio" name="age" value="5">26-27
<input type="radio" name="age" value="7">28-29

<input type="radio" name="bmi" value="0">0-25
<input type="radio" name="bmi" value="0">26-30
<input type="radio" name="bmi" value="9">31-35

So I need to get the value of the checked radio buttons and calculate them 所以我需要获取选中的单选按钮的值并计算它们

Javascript as the first answer that I've got Javascript是我得到的第一个答案

function CalculateValue(){
  //call getAgeValue(), getBmiValue() here and do desired calculations here
}

function getAgeValue()
{
    for (var i = 0; i < document.getElementsByName('age').length; i++)
    {
        if (document.getElementsByName('age')[i].checked)
        {
            return document.getElementsByName('age')[i].value;
        }
    }
}

function getBmiValue()
{
    for (var i = 0; i < document.getElementsByName('bmi').length; i++)
    {
        if (document.getElementsByName('bmi')[i].checked)
        {
            return document.getElementsByName('bmi')[i].value;
        }
    }

Making use of the vanilla document.querySelector 利用香草document.querySelector

function doCalculation(ageValue, bmiValue) {
    // whatever
    return ageValue + bmiValue;
}

function getRadioValue(radio_name) {
    return ( // parenthesis to let us do an OR
      document.querySelector('input[type="radio"][name="' + radio_name + '"]:checked')
      || // or if none is checked
      {} // so we don't get an error
    ).value;
}

function handlerForButton(e) {
    var age = +getRadioValue('age'),
        bmi = +getRadioValue('bmi'),
        foo = doCalculation(age, bmi);
    // do whateverwith foo
    console.log(foo);
}

// after elements exist
document.querySelector('input[type="button"][value="Calculate"]')
    .addEventListener('click', handlerForButton);

DEMO 演示

You may find it easier to use classes and ids to find your elements rather than seeking them out using their other attributes. 您可能会发现,使用ID来查找元素比使用其他属性更容易找到它们。 This would also improve performance 这也将提高性能

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

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