helpdesk
helpdesk

Reputation: 2074

returning a value from a function in jQuery

I have a function in jquery. my function returns a value but when i checked the returned value, I got a 'NAN' what could be the problem:

[CODE]

 var vax = ('#textbox1').val();

 var newVal = calculateMB(vax,11,3.1);
 alert(newVal);

 function calculateMB(num,charge,fixed)
 {
   if(num>50)
   var e = num - 50;
    var new_e = e * charge;
    new_var = new_e / 20;

     return (new_var + fixed);


   }
 [/CODE]

Upvotes: 0

Views: 71

Answers (3)

T.J. Crowder
T.J. Crowder

Reputation: 1074295

You aren't always assigning a value to e, but you're using it in calcuation. Here's that code indented properly:

function calculateMB(num,charge,fixed)
{
    if(num>50)
        var e = num - 50;

    var new_e = e * charge;
    new_var = new_e / 20;
    return (new_var + fixed);
}

When num is <= 50, e never gets a value (and so stays with the default undefined), so e * charge is NaN and NaN propagates through the rest of the calculation.

You probably want:

function calculateMB(num,charge,fixed)
{
    var e, new_e, new_var;

    e = (num > 50) ? num - 50 : num;
    new_e = e * charge;
    new_var = new_e / 20;
    return new_var + fixed;
}

Changes there:

  1. I put all var statements at the top, because that's where they really are.

  2. I declared new_var, which you hadn't declared at all, falling prey to The Horror of Implicit Globals.

  3. I ensured that e always gets assigned a value. I guessed you wanted e to be num when num <= 50, but adjust that as appropriate.

  4. I indented the code consistently. Doing things like consistent code indentation help you avoid bugs, and help others understand your code. Strongly recommend it.

Upvotes: 3

I think it is because the number being read from the text box is a string. Try var vax = Number(('#textbox1').val());

Upvotes: 0

IsisCode
IsisCode

Reputation: 2490

Try

 return (Number(new_var + fixed));

It casts your variable as a number. Also ensure that the parameters being passed to calculateMB are in fact numbers.

Upvotes: -1

Related Questions