user3807733
user3807733

Reputation: 29

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;
        }
    }

Upvotes: 0

Views: 200

Answers (1)

Paul S.
Paul S.

Reputation: 66404

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

Upvotes: 2

Related Questions