Sergio del Amo
Sergio del Amo

Reputation: 78136

Call a function in JavaScript by its name?

I was trying the next code without success

HTML

<a id="addBookButton" href="javascript:showForm('addBookButton','add-book','activateAddBookForm');" class="addA"><span>Add Book</span></a>

Javascript


function showForm(button,form,callback) {
    $("#"+button).hide();
        $("#"+form).show();
        callback();
}

Upvotes: 0

Views: 804

Answers (6)

Gumbo
Gumbo

Reputation: 655825

Try this:

function showForm(button,form,callback) {
    $("#"+button).hide();
    $("#"+form).show();
    if (typeof this[callback] == "function") this[callback]();
}

Of you pass the function by value and not just the name of it:

<a id="addBookButton" href="javascript:showForm('addBookButton','add-book',activateAddBookForm);" class="addA"><span>Add Book</span></a>

Upvotes: 2

mmansoor
mmansoor

Reputation: 620

<a id="addBookButton" onclick="javascript:showForm('addBookButton','add-book','activateAddBookForm');" class="addA"><span>Add Book</span></a>

Javascript

function showForm(button,form,callback) {
  // Your Code
}

function callFunction(){
  document.getElementById('addBookButton').onclick();
}

Upvotes: 0

Sean Bright
Sean Bright

Reputation: 120714

One option is to pass the function be reference instead of as a string, so:

... javascript:showForm('addBookButton','add-book', activateAddBookForm); ....

or to continue using the string:

function showForm(button,form,callback) {
    $("#"+button).hide();
        $("#"+form).show();
        new Function(callback + '();')();
}

Upvotes: -1

PatrikAkerstrand
PatrikAkerstrand

Reputation: 45731

function showForm(button,form,callbackName) {
    $("#"+button).hide();
    $("#"+form).show();
    var callback = window.callbackName;
    if(typeof callback === 'function') {
        callback();
    }
}

Upvotes: 0

AgileJon
AgileJon

Reputation: 53626

You can just pass a reference to the function into your showForm function.

<a id="addBookButton" href="javascript:showForm('addBookButton','add-book',activateAddBookForm);" class="addA"><span>Add Book</span></a>

Upvotes: 5

Hooray Im Helping
Hooray Im Helping

Reputation: 5264

Change your a tag to:

<a id="addBookButton" href="#" onclick="showForm('addBookButton','add-book','activateAddBookForm'); return false;" class="addA"><span>Add Book</span></a>

Note the onclick handler, and the return false; within the onclick.

Upvotes: 0

Related Questions