Javascript calculation resulting NaN - javascript

I have a form to calculate the total value from a form but it results in a nan error even though the values of the html inputs is numerical. What am I doing wrong?
function myFunction() {
var y = document.getElementsByName("optradio").value;
var z = document.getElementsByName("extra-hours").value;
var x = +y + +z;
document.getElementById("result").innerHTML = x;
}
<label class="radio-inline">
<input type="radio" name="optradio" value="25">Half day (3hrs)
</label>
<label class="radio-inline">
<input type="radio" name="optradio" value="50">Full day (6hrs)
</label>
<input type="number" value="" min="0" max="6" class="form-control" name="extra-hours">
<button type="button" onclick="myFunction()">Try it</button>
<p id="result"></p>

You must cycle through the radios to get the value. getElementsByName returns multiple elements.
<label class="radio-inline">
<input type="radio" name="optradio" value="25">Half day (3hrs)
</label>
<label class="radio-inline">
<input type="radio" name="optradio" value="50">Full day (6hrs)</label>
<input type="number" value="" min="0" max="6" class="form-control" name="extra-hours">
<button type="button" onclick="myFunction()">Try it</button>
<p id="result"></p>
<script>
function valueOfRadio(name) {
// Get all of the radios by name
var radios = document.getElementsByName(name);
// Go through each one
for (var i = 0, length = radios.length; i < length; i++) {
// If it's checked, lets return it's value
if (radios[i].checked) {
return radios[i].value;
}
}
}
function myFunction() {
// Go get the right radio value
var y = valueOfRadio('optradio');
// Same problem here. Multiple returned, but we know we only have one element so we index to 0.
//You could alternatively use getElementsById for this which will return a single node.
var z = document.getElementsByName("extra-hours")[0].value;
var x = +y + +z;
document.getElementById("result").innerHTML = x;
}
</script>

getElementsByName returns an array and you have to test all the radios to see if they are checked.
Try it:
<label class="radio-inline">
<input type="radio" name="optradio" value="25">Half day (3hrs)
</label><label class="radio-inline"><input type="radio" name="optradio" value="50">Full day (6hrs)</label>
<input type="number" value="" min="0" max="6" class="form-control" id="extra-hours">
<button type="button" onclick="myFunction()">Try it</button>
<p id="result"></p>
<script>
function myFunction() {
var radios = document.getElementsByName("optradio");
var y = 0;
for (var i = 0, length = radios.length; i < length; i++) {
if (radios[i].checked) {
y += +radios[i].value;
}
}
var z = document.getElementById("extra-hours").value;
var x = +y + +z;
document.getElementById("result").innerHTML = x;
}
</script>

Actually getElementsByName returns array of elements with the name given, name optradio is allocated for 2 radio buttons, so you need to do like this
function myFunction() {
var radioarray = document.getElementsByName("optradio");
var y;
for (var i = 0; i < radioarray.length; i++) {
if (radioarray[i].checked) {
y = radioarray[i].value;
}
}
var z = document.getElementsByName("extra-hours")[0].value;
var x = +y + +z;
document.getElementById("result").innerHTML = x;
}
<label class="radio-inline">
<input type="radio" name="optradio" value="25">Half day (3hrs)
</label>
<label class="radio-inline">
<input type="radio" name="optradio" value="50">Full day (6hrs)
</label>
<input type="number" value="" min="0" max="6" class="form-control" name="extra-hours">
<button type="button" onclick="myFunction()">Try it</button>
<p id="result"></p>

Here is an example using a select instead of radio buttons, and it looks a little more compact and clean. I also used jQUery instead of plain Javascript because the code is a lot cleaner.
function myFunction() {
var result = parseInt($("[name=optradio]").val()) + parseInt($("[name=extra-hours]").val());
$("#result").text(result);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="optradio">
<option value="25">Half day (3hrs)
<option value="50">Full day (6hrs)
</select>
<input type="number" value="0" min="0" max="6" class="form-control" name="extra-hours">
<button type="button" onclick="myFunction()">Try it</button>
<p id="result"></p>

document.getElementsByName("...")
returns a node list, not an individual node. You should use an id to select just a single node (preferred). That is
var y = document.getElementById("optradio").value
var z = document.getElementById("extra-hours").value
The properties "name" and "id" have different meanings, so make sure you use the one you actually mean.
If you want a unique identifier, use "id", if you want to group a selection of your DOM elements, use "name".
Additionally, the value for the radio button is always the same, you need to apply it conditionally based on the 'selected' property.
function myFunction() {
var half = document.getElementById("half");
var full = document.getElementById("full");
var y = half.checked ? half.value : full.value;
var z = document.getElementById("extra-hours").value;
var x = +y + +z;
document.getElementById("result").innerHTML = x;
}
<label class="radio-inline">
<input type="radio" name="optradio" id="half" value="25" checked>Half day (3hrs)
<input type="radio" name="optradio" id="full" value="50">Full day (6hrs)
</label>
<input type="number" value="" min="0" max="6" class="form-control" id="extra-hours">
<button type="button" onclick="myFunction()">Try it</button>
<p id="result"></p>
Finally, although I'm not going to show it, you're probably best learning jQuery now; everything else uses jQuery. Everyone uses jQuery because it's better than base javascript. As Christian Juth showed in his answer, you probably want to make it a selection box, too.

Related

How to subtract two div by their ID?

I have some range sliders and input fields. From that I'm getting some equations now I want to subtract those dynamic numbers by their ID. Below is the code but I'm getting NaN value. Below the steps, I've done.
Getting #totalavgtime from the multiplication of range slider and .averagetime
Getting #timetoproduce from the multiplication of range slider and .radio-roi next input value.
Now trying to subtract #totalavgtime - #timetoproduce but getting NaN value in #timesaving.
$(document).ready(function() {
$(".range").on("change", function() {
var mult = 0;
$('.range').each(function(i) {
var selector_next = parseInt($(".averagetime:eq(" + i + ")").attr("value"))
mult += parseInt($(this).val()) * selector_next //multply..
console.log($(".averagetime:eq(" + i + ")").attr("value"), $(this).val())
})
$("#totalavgtime").val(mult)
})
});
$(document).ready(function() {
$('.range').on('change', function() {
let n = $(this).attr('id').match(/\d+/g)[0];
let total = 0;
let checkVal = $('.radio-roi:checked').next('input').val();
let multiplyFactor = parseFloat(checkVal);
console.log(multiplyFactor)
$('.range').each(function() {
total += (parseFloat($(this).val()) * multiplyFactor);
});
$('#timetoproduce').value(total);
})
});
$(document).ready(function() {
var txt1 = parseInt(document.getElementById("totalavgtime").value);
var txt2 = parseFloat(document.getElementById("timetoproduce").value);
var res = document.getElementById("timesaving");
Number(txt1);
Number(txt2);
//Substract that
res.value = txt1 - txt2;
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<input type="radio" id="" class="radio-roi" name="plan" value="plus" checked>
<input type="text" value="2.5" id="actualtime2" class="hiden-actual-time" disabled><br>
<input type="radio" id="" class="radio-roi" name="plan" value="pro">
<input type="text" value="3" id="actualtime3" class="hiden-actual-time" disabled><br>
<input type="text"value="6" id="avgtime-id" class="averagetime"disabled><br>
<input type="range" name="slider-1" min="0" max="12" value="0" step="1" class="range" id="range-slider"><br>
<input type="text"id="totalavgtime" value="" disabled><br>
<input type="text"id="timetoproduce" value="" disabled><br>
<input type="text"id="timesaving" value="" disabled><br>
You can merge both event handler in one as both are triggering same elements . So , inside this on each iteration get value of range slider and add total to same variable and set them in required input . Now , to subtract them check if the value is not null depending on this take value of input else take 0 to avoid NaN error.
Demo Code :
$(document).ready(function() {
$(".range").on("change", function() {
$(this).next().text($(this).val()) //for output(range)
var selector_next_avg = 0;
var timetoproduce = 0
var checkVal = parseFloat($('.radio-roi:checked').next('input').val()); //radio next input
$('.range').each(function(i) {
var selector_next = parseInt($(".averagetime:eq(" + i + ")").val()) //avg..input
selector_next_avg += parseInt($(this).val()) * selector_next;
timetoproduce += (parseFloat($(this).val()) * checkVal);
})
//set both values
$("#totalavgtime").val(selector_next_avg)
$('#timetoproduce').val(timetoproduce);
total() //call to total..(sub)
})
});
function total() {
var txt1 = $("#totalavgtime").val() != "" ? parseFloat($("#totalavgtime").val()) : 0; //if null take 0
var txt2 = $("#timetoproduce").val() != "" ? parseFloat($("#timetoproduce").val()) : 0;
$("#timesaving").val(txt1 - txt2); //set value
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<input type="radio" id="" class="radio-roi" name="plan" value="plus" checked>
<input type="text" value="2.5" id="actualtime2" class="hiden-actual-time" disabled><br>
<input type="radio" id="" class="radio-roi" name="plan" value="pro">
<input type="text" value="3" id="actualtime3" class="hiden-actual-time" disabled><br>
<input type="text" value="6" id="avgtime-id" class="averagetime" disabled><br>
<input type="range" name="slider-1" min="0" max="12" value="0" step="1" class="range" id="range-slider"><output></output><br>
<input type="text" id="totalavgtime" value="" disabled><br>
<input type="text" id="timetoproduce" value="" disabled><br>
<input type="text" id="timesaving" value="" disabled><br>

DOM javascript Form Gender Radio button "on" value output

function myfunction() {
var x = document.getElementById("myform").elements;
var para = x[0].value;
for (var i = 0; i < x.length; i++) {
para = para.concate(x[i].value);
}
document.getElementById("demo").innerHTML = para;
}
<form id="myform">
name<input type="textbox" name="fname"> email
<input type="textbox" name="email"> number
<input type="textbox" name="number"> Gender
<input type="radio" name="gender" checked>Male
<input type="radio" name="gender">Female
<button type="button" onclick="myfunction()"> Click me</button>
</form>
<p id="demo"></p>
I tried but i think there is a bug. I want to display whole line that the user enter but clicking it is not working. At mid, it was working but after not working. I want output as jaykumar jay#123 111111 Male . And also how to get Gender Male/Female in demo. Instead it is giving me only "on" .How to get value Male or Female in demo.
Because you didn't add value to radio input. According to Mozilla doc:
If you omit the value attribute in the HTML, the submitted form data assigns the value on to the group.
function myfunction() {
var x = document.getElementById("myform").elements;
var para = x[0].value;
for (var i = 0; i < x.length; i++) {
para = para.concat(x[i].value);
}
document.getElementById("demo").innerHTML = para;
}
<form id="myform">
name<input type="textbox" name="fname"> email
<input type="textbox" name="email"> number
<input type="textbox" name="number"> Gender
<input type="radio" checked id="male" name="gender" value="Male">
<label for="male">Male</label>
<input type="radio" id="female" name="gender" value="Female">
<label for="female">Female</label>
<button type="button" onclick="myfunction()"> Click me</button>
</form>
<p id="demo"></p>
you need to have a different treatment when it's a radio, in addition of adding the value for each radio
function myfunction() {
var x = document.getElementById("myform").elements;
var para = x[0].value;
for (var i = 0; i < x.length; i++) {
if ((x[i].type === 'radio' && x[i].checked) || x[i].type === 'text') {
para = para.concate(x[i].value);
}
}
document.getElementById("demo").innerHTML = para;
}
<form id="myform">
name<input type="text" name="fname"> email
<input type="text" name="email"> number
<input type="text" name="number"> Gender
<input type="radio" value="Male" name="gender" checked>Male
<input type="radio" value="Female" name="gender">Female
<button type="button" onclick="myfunction()"> Click me</button>
</form>
<p id="demo"></p>

I cannot get the javaScript to do the function i am requesting it to do, in my case multiply two values by a hidden and then add a final value

I am so lost as to why this is not working properly, as it is on similar previous code. This is for field personnel, a cheat Sheet to simply enter values and get a fast answer (calculation). They enter the value of Num5/6/7 code multiplies 3 values one hidden then adds the last value together and upon click button the result is shown.
Here is my code (taken from copy/paste of a working conversion).
<div class="containerHydro">
<p>
<label >Fluid Column Length</label>
<input type="number" id="num5">
<label >Fluid Weight</label>
<input type="number" id="num6">
<label >Well Head Pressure</label>
<input type="number" id="num7">
<p>
<input type="button" value="Sum" onclick="calculate()"/>
</p>
<p id="total1"></p>
</div>
The Function also copy/paste of multiply two int then divide by hidden (which works BTW)
function calculate() {
var numFive = document.getElementById('num5').value;
var numSix = document.getElementById('num6').value;
var numSvn = document.getElementById('num7').value;
var total1 = parseInt(numFive) * parseInt(numSix) * 0.052 + parseInt('numSvn');
var p =document.getElementById('total1');
p.innerHTML += total1;
}
Here is the same idea which works fine-
Code-
<div class="container7">
<p>
<label id="H2S Percent">H2S Percentage</label>
<input id="num3" type="number" name="num3" placeholder="H2S Percent">
<label id="H2S Percent">WHP</label>
<input id="num4" type="number" name="num4"placeholder="Well Head Pressure" > <br>
</p>
<input type="button" value="H2S Partial Pressure" onclick="math()"/>
<p id="result"></p>
</div>
Function
function math() {
var numThree = document.getElementById('num3').value;
var numFour = document.getElementById('num4').value;
var result = parseInt(numThree) * parseInt(numFour) / 1000000;
var p = document.getElementById('result');
p.innerHTML += result;
}
function calculate() {
var numFive = document.getElementById('num5').value;
var numSix = document.getElementById('num6').value;
var numSvn = document.getElementById('num7').value;
var total1 = parseInt(numFive) * parseInt(numSix) * 0.052 + parseInt(numSvn);
var p = document.getElementById('total1');
p.innerHTML += total1;
}
input {
display: block;
}
<div class="containerHydro">
<p>
<label>Fluid Column Length</label>
<input type="number" id="num5">
<label>Fluid Weight</label>
<input type="number" id="num6">
<label>Well Head Pressure</label>
<input type="number" id="num7">
<p>
<input type="button" value="Sum" onclick="calculate()" />
</p>
<p id="total1"></p>
</div>

How to be simpler in this JavaScript?

I am trying to make a Js to search & filter items in JSON
so I use many radio in the "form" , the result will be [X,X,X,X,X,X]
I will set 50tags x 3(choose), I can feel my function will be large.
What ways can I change my function to be simpler?
function myFunction() {
var elements1 = document.getElementsByName("chair"),
elements2 = document.getElementsByName("car"),
elements3 = document.getElementsByName("house"),
elements4 = document.getElementsByName("tree"),
elements5 = document.getElementsByName("flower"),
elements6 = document.getElementsByName("grass");
var i;
for (var a = "", i = elements1.length; i--;) {
if (elements1[i].checked) {
var a = elements1[i].value;
break;
}
};
for (var b = "", i = elements2.length; i--;) {
if (elements2[i].checked) {
var b = elements2[i].value;
break;
}
};
for (var c = "", i = elements3.length; i--;) {
if (elements3[i].checked) {
var c = elements3[i].value;
break;
}
};
for (var d = "", i = elements4.length; i--;) {
if (elements4[i].checked) {
var d = elements4[i].value;
break;
}
};
for (var e = "", i = elements5.length; i--;) {
if (elements5[i].checked) {
var e = elements5[i].value;
break;
}
};
for (var f = "", i = elements6.length; i--;) {
if (elements6[i].checked) {
var f = elements6[i].value;
break;
}
};
var o2 = document.getElementById("output2");
o2.value = "[" + a + "," + b + "," + c + "," + d + "," + e + "," + f + "]";
o2.innerHTML = o2.value;
}
<form><input type="radio" id="chair1" name="chair" class="chair" value="1">
<input type="radio" id="chair0" name="chair" class="chair" value="0" checked>
<input type="radio" id="chair-1" name="chair" class="chair" value="-1">
<input type="radio" id="car1" name="car" class="car" value="1">
<input type="radio" id="car0" name="car" class="car" value="0" checked>
<input type="radio" id="car-1" name="car" class="car" value="-1">
<input type="radio" id="house1" name="house" class="house" value="1">
<input type="radio" id="house0" name="house" class="house" value="0" checked>
<input type="radio" id="house-1" name="house" class="house" value="-1">
<input type="radio" id="tree1" name="tree" class="tree" value="1">
<input type="radio" id="tree0" name="tree" class="tree" value="0" checked>
<input type="radio" id="tree-1" name="tree" class="tree" value="-1">
<input type="radio" id="flower1" name="flower" class="flower" value="1">
<input type="radio" id="flower0" name="flower" class="flower" value="0" checked>
<input type="radio" id="flower-1" name="flower" class="flower" value="-1">
<input type="radio" id="grass1" name="grass" class="grass" value="1">
<input type="radio" id="grass0" name="grass" class="grass" value="0" checked>
<input type="radio" id="grass-1" name="grass" class="grass" value="-1">
<div> <input type="button" value="Search" id="filter" onclick="myFunction()" /> </div>
</form>
<div id="output2"></div>
Give the form an id, and you can refer to it as an object.
function myFunction() {
var form = document.getElementById("myForm");
var parts = [
form.chair.value,
form.car.value,
form.house.value,
form.tree.value,
form.flower.value,
form.grass.value
];
var o2 = document.getElementById("output2");
o2.innerHTML = '[' + parts.join(',') + ']';
}
And this is an even simpler solution using a FormData object. It supports an arbitrary number of named form fields without having to actually name them in the function:
function myFunction() {
var myForm = document.getElementById('myForm');
var formData = new FormData(myForm);
var parts = Array.from(formData.values());
var o2 = document.getElementById("output2");
o2.innerHTML = '[' + parts.join(',') + ']';
}
Use document.querySelector() to directly select the value of the checked radio button based on element names.
function myFunction() {
var chair = document.querySelector('input[name="chair"]:checked').value;
var car = document.querySelector('input[name="car"]:checked').value;
var house = document.querySelector('input[name="house"]:checked').value;
var tree = document.querySelector('input[name="tree"]:checked').value;
var flower = document.querySelector('input[name="flower"]:checked').value;
var grass = document.querySelector('input[name="grass"]:checked').value;
var o2 = document.getElementById("output2");
o2.value = "[" + chair + "," + car + "," + house + "," + tree + "," + flower + "," + grass + "]";
o2.innerHTML = o2.value;
}
Use arrays!
function myFunction() {
var elem_ids = [ "chair", "car", "house", "tree", "flower", "grass"];
var elems = elem_ids.map(id => document.getElementById(id));
var elems_check_values = elems.map(el => {
// el is kind of an array so
for(var i = 0; i < el.length; ++i)
if(el[i].checked)
return el[i].value;
return undefined;
}).filter(value => value == undefined) // to filter undefined values;
var output = "[" + elems_check_values.join(",") + "]";
var o2 = document.getElementById("output2");
o2.innerHTML = output
}
Your issue can be generalized to: how can I aggregate values for all fields in a given form?
The solution is a function that can be merely as long as 5 lines, and work for any amount of inputs with any type. The DOM model for <form> elements provides named keys (eg, myform.inputName) which each have a value property. For radio buttons, eg myform.tree.value will automatically provide the value of the selected radio button.
With this knowledge, you can create a function with a simple signature that takes a form HTMLElement, and an array of field names for the values that you need, like below: (hit the search button for results, and feel free to change the radio buttons).
function getFormValues(form, fields) {
var result = [];
for (var i = 0; i < fields.length; i++) {
result.push(form[fields[i]].value);
}
return result;
}
document.getElementById('filter').addEventListener('click', function(e) {
var o2 = document.getElementById("output2");
o2.innerHTML = getFormValues(document.forms[0], ['chair','car','house','tree','flower','grass']);
});
<form><input type="radio" id="chair1" name="chair" class="chair" value="1">
<input type="radio" id="chair0" name="chair" class="chair" value="0" checked>
<input type="radio" id="chair-1" name="chair" class="chair" value="-1">
<input type="radio" id="car1" name="car" class="car" value="1">
<input type="radio" id="car0" name="car" class="car" value="0" checked>
<input type="radio" id="car-1" name="car" class="car" value="-1">
<input type="radio" id="house1" name="house" class="house" value="1">
<input type="radio" id="house0" name="house" class="house" value="0" checked>
<input type="radio" id="house-1" name="house" class="house" value="-1">
<input type="radio" id="tree1" name="tree" class="tree" value="1">
<input type="radio" id="tree0" name="tree" class="tree" value="0" checked>
<input type="radio" id="tree-1" name="tree" class="tree" value="-1">
<input type="radio" id="flower1" name="flower" class="flower" value="1">
<input type="radio" id="flower0" name="flower" class="flower" value="0" checked>
<input type="radio" id="flower-1" name="flower" class="flower" value="-1">
<input type="radio" id="grass1" name="grass" class="grass" value="1">
<input type="radio" id="grass0" name="grass" class="grass" value="0" checked>
<input type="radio" id="grass-1" name="grass" class="grass" value="-1">
<div> <input type="button" value="Search" id="filter"/> </div>
</form>
<div id="output2"></div>
The thing you need to do is break the code up into reusable chunks. So make a method to get the value. That will reduce a lot of code. After than, you should look at a way to reduce how many elements you need to list. Finally, find an easy way to fetch all the values.
So below is code that does this. It uses a helper method to get the elements, find the value. Than it uses an array to know what element groups to look for. And finally it uses map to iterate over the list so you do not have to code multiple function calls.
function getSelected (radioBtnGroup) {
// get the elements for the radio button group
var elms = document.getElementsByName(radioBtnGroup)
// loop over them
for(var i=0; i<elms.length; i++) {
// if checked, return value and exit loop
if (elms[i].checked) {
return elms[i].value
}
}
// if nothing is selected, return undefined
return undefined
}
// list the groups you want to get the values for
var groups = ['rb1', 'rb2', 'rb3', 'rb4']
// call when you want to get the values
function getValues () {
// use map to get the values of the rabio button groups.
// map passes the index value as the first argument.
// code is map(function(k){return getSelected(k)})
var results = groups.map(getSelected)
//displat the results
console.log(results);
}
document.querySelector('#btn').addEventListener('click', getValues);
<form>
<fieldset>
<legend>Item 1</legend>
<label><input type="radio" name="rb1" value="1-1"> One</label>
<label><input type="radio" name="rb1" value="1-2"> Two</label>
<label><input type="radio" name="rb1" value="1-3"> Three</label>
</fieldset>
<fieldset>
<legend>Item 2</legend>
<label><input type="radio" name="rb2" value="2-1"> One</label>
<label><input type="radio" name="rb2" value="2-2"> Two</label>
<label><input type="radio" name="rb2" value="2-3"> Three</label>
</fieldset>
<fieldset>
<legend>Item 3</legend>
<label><input type="radio" name="rb3" value="3-1"> One</label>
<label><input type="radio" name="rb3" value="3-2"> Two</label>
<label><input type="radio" name="rb3" value="3-3"> Three</label>
</fieldset>
<fieldset>
<legend>Item 4</legend>
<label><input type="radio" name="rb4" value="4-1"> One</label>
<label><input type="radio" name="rb4" value="4-2"> Two</label>
<label><input type="radio" name="rb4" value="4-3"> Three</label>
</fieldset>
<button type="button" id="btn">Get Results</button>
</form>
Personally I would not store the values in an array, I would use an object with key value pairs.
var results = groups.reduce(function (obj, name) {
obj[name] = getSelected(name)
return obj
}, {});

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

Categories

Resources