简体   繁体   中英

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

My code so far is: 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

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

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. This would also improve performance

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