1

I am trying to assign a string as the name of a function within the jQuery code but there is something wrong with what I am doing. In the code below, I am passing name="hello" as the function name and msg="hello world!" as the argument. I am trying to call the hello(msg) function. Any help will be appreciated.

http://jsfiddle.net/7jhveokn/

HTML

`<input type="button" value="Click me!">`

CSS

input{
    width: 100px;
}

jQuery

$(document).ready(function(){

$('input').click(function(){
    var name = 'hello';
    var msg = 'hello world!';
    window[name](msg);
});

function hello(msg){
    alert(msg);
}
});
blank_kuma
  • 335
  • 6
  • 16

3 Answers3

7

You have defined the method hello with the closure of the dom ready handler, so it won't be a property of the window object, only global variables/function are accesible as property of window object.

So either assign it as a property of the window object

$(document).ready(function() {

  $('input').click(function() {
    var name = 'hello';
    var msg = 'hello world!';
    window[name](msg);
  });

  window.hello = function hello(msg) {
    alert(msg);
  }
});
input {
  width: 100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="button" value="Click me!">

Or define it outside of the closure

$(document).ready(function() {
  $('input').click(function() {
    var name = 'hello';
    var msg = 'hello world!';
    window[name](msg);
  });
});

function hello(msg) {
  alert(msg);
}
input {
  width: 100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="button" value="Click me!">

But a more appropriate approach could to use a different object than the window object like

$(document).ready(function() {

  $('input').click(function() {
    var name = 'hello';
    var msg = 'hello world!';
    fns[name](msg);
  });

  var fns = {};
  fns.hello = function hello(msg) {
    alert(msg);
  }
});
input {
  width: 100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="button" value="Click me!">
Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
0

$(document).ready(function(){

$('input').click(function(){
    var name = 'hello';
    var msg = 'hello world!';
    //window[name](msg);
    eval(
        'function '+name+'(msg){ alert(msg); }');
    );

});

});

-1
window.hello = function(msg) {
  alert(msg);
};
zuo
  • 1,061
  • 1
  • 12
  • 27