Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript undefined but formula is present

Tags:

javascript

I'm really scratching my head at this one. I'm getting an error that calculateHelper is undefined... but.... isn't it right in the function?? I first thought it was an order thing, so I've even moved the entire var calculateHelper to above the if(valuesArr) statement, or moved it outside the buy_vs_rent event handler, none of that helped.

$('#buy_vs_rent_calculate').on('click', function(){

  if(valuesArr.length === 1){
    setTimeout("calculateHelper(valuesArr[0])",100);
  } else {
    alert("Please set three of the four values using the sliders; leave only one field blank to be calculated")
  }

  var calculateHelper = function(valueToCalc){
    ... 
  };
});
like image 239
james Avatar asked Mar 08 '26 15:03

james


2 Answers

When you pass a string to setTimeout it is resolved to code in the global context. However your calculateHelper is defined as a local variable.

$('#buy_vs_rent_calculate').on('click', function(){

  if(valuesArr.length === 1){
    setTimeout(function () { calculateHelper(valuesArr[0]); },100);
  } else {
    alert("Please set three of the four values using the sliders; leave only one field blank to be calculated")
  }

  var calculateHelper = function(valueToCalc){
    ... 
  };
});
like image 122
Igor Avatar answered Mar 10 '26 03:03

Igor


Because calculateHelper is defined locally and calling a function (calculateHelper(valuesArr[0])) doesn't make it a function (as said by @Spencer Wieczorek) --> setTimeout first parameter must be a function reference, change it into something like this:

$('#buy_vs_rent_calculate').on('click', function(){
  var calculateHelper = function(valueToCalc){
    ... 
  }; // move up
  if(valuesArr.length === 1){
    setTimeout(function(){
      calculateHelper(valuesArr[0]); // don't use string for local function
    },100);
  } else {
    alert("Please set three of the four values using the sliders; leave only one field blank to be calculated")
  }
});
like image 35
Kokizzu Avatar answered Mar 10 '26 05:03

Kokizzu