views:

167

answers:

1

Hi SO,

I am trying to learn JavaScript but I've come across a hurdle. If the answer is obvious and reachable through a simple search I apologize in advance. I am a novice to programming and JavaScript, and unsure what line of inquiry to follow.

In the following code, the function takes values from a HTML form, does some processing and sends them back. I've tested the input and output process and it's working correctly.

function foo() {

var x = parseInt(document.formdata.fieldone.value);
var y = parseFloat(document.formdata.fieldtwo.value);

if (isNaN(y))
    { var z = x; }
else
    { var z = function(x, y) {
            if ((y * (x / 100)) < 1) {
                return (x + Math.ceil(y * (x / 100))); }
            else if ((y * (x / 100)) > 1) {
                return (x + Math.round(y * (x / 100))); }
            else {
                return 0; } } }

var bar = document.getElementById("output");

bar.innerHTML = z; }

The problem is, when the else branch of the conditional statement tries to process the anonymous function, the return value isn't assigned; rather the entirety of the function as a string. That is, the following appears in the HTML page:

function (x, y) { if ((y * (x / 100)) < 1) { return (x + Math.ceil(y * (x / 100))); } else if ((y * (x / 100)) > 1) { return (x + Math.round(y * (x / 100))); } else { return 0; } }

I've tested the code in Chrome and Firefox and the result is the same.

Any help is appreciated and thank you in advance.

+2  A: 

You need to call the function by passing it two arguments, because otherwise the z variable will just store a reference to this function but it will not evaluate it:

var z = (function(x, y) {
    if ((y * (x / 100)) < 1) {
        return (x + Math.ceil(y * (x / 100))); }
    else if ((y * (x / 100)) > 1) {
        return (x + Math.round(y * (x / 100))); }
    else {
        return 0; 
    } 
})(x, y);

Note that (x, y) used inside the anonymous function are not the same as the one passed as arguments at the end which correspond to the two variables declared in the beginning of the foo function.

Darin Dimitrov
Thank you, calling the function always helps :)
Omega