0

how can I use function name passed as argument.

example:

showError('container', 'id', '- message', 'show');
showError('container', 'id', '', 'hide');


function showError(container, id, msg, action)
{    
    if(action == 'show') {  
        $('#' + container).show();       
        $('#' + id).html(msg).show();
    }
    else {  
        $('#' + container).hide();       
        $('#' + id).html(msg).hide();
    }

}
Umar Adil
  • 5,128
  • 6
  • 29
  • 47
  • try eval() http://stackoverflow.com/questions/86513/why-is-using-the-javascript-eval-function-a-bad-idea – LosManos Aug 01 '12 at 18:07
  • 1
    @LosManos: -1. [Read](http://stackoverflow.com/a/87260/1048572) before you link, and then don't do it. – Bergi Aug 01 '12 at 18:13
  • @Bergi: yes? I tried to say that eval was an option but without having to write text that explained the pros and cons of it. The other answers are way better though - hence only a comment. – LosManos Aug 03 '12 at 17:13

3 Answers3

3

obj.foo() really is a 2 step thing. obj.foo returns a function object, and then the () executes it. obj['foo'] returns the same function object, so add a () to execute it.

Since obj['foo'] is the same as obj.foo. Even if the value on that property is a function. So you can always access any property with the [] accessor, using a string as the key name.

$('#' + container)[action]();
Alex Wayne
  • 178,991
  • 47
  • 309
  • 337
2

Use bracket notation to access the respective method by a string:

function showError(container, id, msg, action) {    
    $('#' + container)[action]();       
    $('#' + id).html(msg)[action]();
}

However, your method looks strange. I'd recommend to limit the action to the two values, and do that automatically:

function showError(container, id, msg) {
    var action = msg=='' ? 'hide' : 'show';
    $('#' + container)[action]();       
    $('#' + id).text(msg)[action]();
}
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
2

In the general case, the bracket notation is good. In your case, use toggle:

function showError(container, id, msg, action)
{    
        $('#' + container).toggle(action === 'show');       
        $('#' + id).html(msg).toggle(action === 'show');
}

or even (as Bergi suggests):

function showError(container, id, msg)
{    
        $('#' + container).toggle(!!msg);       
        $('#' + id).html(msg);
}

(It uses my own invention, the double-bang !!, which converts truthy or falsy values to their Boolean equivalents.)

Michael Lorton
  • 43,060
  • 26
  • 103
  • 144