Reputation: 118
I have two JavaScript function. I want to call a function by another function argument. Like this code:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv='Content-type' content='text/html; charset=utf-8'>
<title>Javascript Function</title>
<script language="javascript" type="text/javascript">
function fOne()
{
alert("Function One");
}
function fTwo(f_name)
{
f_name; // I want to Call fOne() here
}
</script>
</head>
<body>
<a href="#" onclick="fTwo('fOne')">Call Function</a>
</body>
</html>
Is this posible in any way?
Upvotes: 2
Views: 90
Reputation: 6583
You can do this:
function one() {
alert('one');
}
function two(fname) {
window[fname]();
}
two('one');
For a more complete answer, see here: How to execute a JavaScript function when I have its name as a string
Upvotes: 3
Reputation: 105886
The best way to do this is to pass a reference to your function (fOne
) and not a string (other answers are already covering this). However, if you really want to call your function by its name, you can look it up in the window
object:
function fOne(){ console.log("fOne"); }
function fCall (f_name) {
window[f_name]();
}
fCall("fOne"); // results in console.log.
However, stringly code tends to be more error prone, so use the method provided by Akshay or Rahul instead.
Upvotes: 1
Reputation: 172428
Try like this:-
<!DOCTYPE html>
<html>
<head>
<meta http-equiv='Content-type' content='text/html; charset=utf-8'>
<title>Javascript Function</title>
<script language="javascript" type="text/javascript">
function fOne()
{
alert("Function One");
}
function fTwo(f_name)
{
f_name(); // I want to Call fOne() here
}
</script>
</head>
<body>
<a href="#" onclick="fTwo(fOne)">Call Function</a>
</body>
</html>
Upvotes: 1
Reputation: 1570
<!DOCTYPE html>
<html>
<head>
<meta http-equiv='Content-type' content='text/html; charset=utf-8'>
<title>Javascript Function</title>
<script language="javascript" type="text/javascript">
function fOne()
{
alert("Function One");
}
function fTwo(f_name)
{
f_name(); // I want to Call fOne() here
}
</script>
</head>
<body>
<a href="#" onclick="fTwo(fOne)">Call Function</a>
</body>
</html>
This is all that you need
Upvotes: 4
Reputation: 4744
function fTwo(f_name)
{
eval(f_name+"()");
}
I'll let someone cleverer than I explain the security implications.
Upvotes: -1