Aim: This chunk of js, is designed to grab values entered into fields in a form, assign them to variables and then perform a calculation which outputs into a field on that page.
There is a short function that means out put is set as Unknown if any of the variables are undefined or empty.
My code:
function calculate() {
var $u5pop = $('input[name=sv_21d]').val();
var $sam = $('input[name=sv_25d]').val();
var $incidence = $('input[name=sv_313]').val();
var $treated = $('input[name=sv_312]').val();
if ($u5pop == undefined ||$u5pop == '') {
$u5pop = 0;
}
else {
$u5pop = parseFloat($u5pop);
}
if ($sam == undefined ||$sam == '') {
$sam = 0;
}
else {
$sam = parseFloat($sam);
}
if ($incidence == undefined || $incidence == '') {
$incidence = 0;
}
else {
$incidence = parseFloat($incidence);
}
//
if ($treated == undefined || $treated == '') {
$treated = 0;
}
else {
$treated = parseFloat($treated);
}
var $determined = $u5pop / $incidence * $treated * $sam;
if ($determined == undefined || $determined == '') {
$determinedOut = 'Unknown';
}
else {
$determinedOut = parseFloat($determined);
}
$('#calculation').attr('value', $determinedOut.toFixed(2));
}
The output field div #calculation is:
<input size="18" class="calculation" id="calculation" value="Click to calculate" onfocus="calculate()"/>
Such that when user click within the field it performs the calculation.
This is a structure / syntax issue I think, but everything looks good to me. Would anyone with more experienced eyes be able to see where I'm going wrong here? At current: nothing happens (the default value remains).
Many thanks!
EDIT: This works perfectly so long as all the fields are filled in, however it FAILSS to output 'unknown' if the fields are left empty and the function is called by onfocus