-1

I have a javascript function defined like this

function is_mandatory(string){
     if(string.length > 0 )
 return true;   
}

Now, i am trying to call the function defined as a sting name

var is_mandatory; 

is_mandatory("Check"); 

But, this returns an error saying variable is not a function. How can I call the function from a string name.

Cheers!

verdure
  • 3,201
  • 6
  • 26
  • 27
  • You have defined variable with same name as method and that's why you are getting such an error. Try changing variable name of `var is_mandatory;`. – Harry Joy Dec 05 '11 at 06:08
  • You're not trying to call the function defined as a string name. – Dave Newton Dec 05 '11 at 06:09
  • possible duplicate of [How to execute a JavaScript function when I have its name as a string](http://stackoverflow.com/questions/359788/how-to-execute-a-javascript-function-when-i-have-its-name-as-a-string) – Strelok Dec 05 '11 at 06:12
  • Your definition of is_mandatory will return `undefined` if you pass in a string whose length === 0. I don't think this is intended. – helpermethod Dec 05 '11 at 07:41

4 Answers4

2

This will work.

function is_mandatory(str){
     return (str.length > 0 );
}

is_mandatory("Check"); 

You do not have to declare var for is_mandatory

OnesimusUnbound
  • 2,886
  • 3
  • 30
  • 40
0

You are re-defining is_mandatory as an undefined variable when you run this code:

var is_mandatory;

But I don't think that is your intent. Just delete that var line completely.

Blender
  • 289,723
  • 53
  • 439
  • 496
0

If your variable is declared in the window's scope you can do this:

function is_mandatory(str){
    if(window[str].length > 0 )
        return true;   
}

JS Fiddle Example

Paul
  • 139,544
  • 27
  • 275
  • 264
-2

Initialize you variable with your function, and then try to call it.

var is_mandatory = is_mandatory;

is_mandatory("Check");
Andrey Selitsky
  • 2,584
  • 3
  • 28
  • 42