JJJ
JJJ

Reputation: 49

Javascript form NAN error

Firstly I apologies, I've just starting out with JavaScript

I have a problem with a form. I have two groups of Radio buttons on the form (age and bmi)

Everytime the 'Calculate' button is clicked, I want add the values of each checked Radio button and alert this to the screen.

It works in Chrome, but ALL other browsers give an NAN error.

Can anyone help?

<br>
<input type="radio" name="age" class="myradioButton" value = "1"/>
<input type="radio" name="bmi" class="myradioButton" value = "3"/>
<input type="button" name="Calculate" id="calculate"onclick="calculatehealth()" value="Calculate"/>
<br>
<script>
    function calculatehealth() {
        var valueAge  = document.forms['myForm'].elements["age"].value;
        var valueint = parseInt(valueAge);

        var valueBmi =  document.forms['myForm'].elements["bmi"].value;
        var Bmiint = parseInt(valueBmi);

        var total = Bmiint + valueint;

        alert(total);
    }

Upvotes: 0

Views: 579

Answers (1)

Asons
Asons

Reputation: 87191

Demo: http://jsfiddle.net/z4RKx/

HTML

<form id="myForm">
    <input type="radio" name="age" class="myradioButton" value="1" />
    <input type="radio" name="bmi" class="myradioButton" value="3" />
    <input type="button" name="Calculate" value="Calculate" onclick='calculatehealth()' />
</form>

JS

function calculatehealth() {

    var valueint = 0;

    if (document.forms['myForm'].elements["age"].checked) {
        valueint += parseInt(document.forms['myForm'].elements["age"].value);
    }

    if (document.forms['myForm'].elements["bmi"].checked) {
        valueint += parseInt(document.forms['myForm'].elements["bmi"].value);
    }

    alert(valueint);

}

And if you have many elements this might be a good alternative:

function calculatehealth() {

    var valueint = 0;

    for(i = 0; i < document.forms['myForm'].elements.length; i++) {
        if (document.forms['myForm'].elements[i].checked) {
            valueint += parseInt(document.forms['myForm'].elements[i].value);
        }
    }

    alert(valueint);

}

Upvotes: 2

Related Questions