3

It is a bit complicated for to explain properly what I mean, so please try to understand me :)

I want to be able in javascript to call a element method/function using text sent as parameter. For example:

function CallAFunction(function_name){
 document.getElementById('some_id').function_name();
}

As you see in the above example, I want to send function_name as parameter, and it is type of string or a simple text. So how I can use this function name to call it like that ?

Or, please suggest me something which may help me get the same as I need.

2
  • 1
    document.getElementById('some_id')[function_name](); In JavaScript, x.y is the same as x["y"] Commented Mar 7, 2013 at 18:19
  • @RaymondChen you are absolutely right. Thanks! Commented Mar 7, 2013 at 18:35

2 Answers 2

6

Use bracket notation;

document.getElementById('some_id')[function_name]();
Sign up to request clarification or add additional context in comments.

6 Comments

Thank you my friend, you give me a very quick answer, I'm happy, and I will mark this answer as accepted.
by the way, what will happen if function name not exist for that element ? it will crash the code after it ?
@JigsweelJigsweel yes it will. May want to check elem.hasOwnProperty(function_name) first and even check if it's callable
cool, didn't know about that method, and how to check if it's callable ?
@JigsweelJigsweel no set way, but typeof(elem[function_name]) === 'function' should generally work
|
0

call function name using string :

var myFunc = window[myFuncName];

you can sent parameter like this :

<button onclick="myFunction('Harry Potter','Wizard')">Try it</button>

<script>
function myFunction(name,job)
{
alert("Welcome " + name + ", the " + job);
}
</script>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.