0

I've got a pretty basic jQuery question. I'm trying to trigger an existing function depending on the option chosen from a select list.

Example HTML:

<select name="selectAction" id="selectAction">
  <option>Choose an action</option>
  <option value="firstFunction">First Function</option>
  <option value="secondFunction">Second Function</option>
  <option value="thirdFunction">Third Function</option>
</select>

The goal is to run firstFunction() if that option is selected, secondFunction() if that one is chosen, etc.

I can get the value of the select list, but not sure how to use that to execute a specific function.

So I have this, so far:

$(document).ready(function() {
$('body').on('change', '#selectAction', function(e) {
    var theValue = $(this).find(":selected").val();
});

});

I know I could use eval() to handle this - eval(theValue + '()'); - but I'm trying to avoid that course. I also realize I could use a series of if/else or switch/case statements, but that seems a little inelegant. Is there a way to trigger the function based on the value name itself?

TIA - Joe

Joe Lowery
  • 562
  • 11
  • 26
  • 1
    Put those functions into object `{name: func, name2: func2}[nameToBeCalled]()` – Yury Tarabanko Nov 28 '14 at 23:09
  • Is this what you are asking about? http://stackoverflow.com/a/3326095/903014 – Steve0 Nov 28 '14 at 23:09
  • @YuryTarabanko - I'm sorry, I don't know what you mean. Can you clarify? – Joe Lowery Nov 28 '14 at 23:20
  • Create an object: `var API = {firstFunction: firstFunction, ...}`. And use it like this: `$('#selectAction').change(function(){API[$(this).val()]();})` – Yury Tarabanko Nov 28 '14 at 23:21
  • @Steve - I thought that might be the answer too, so I tried adding `$('html')[theValue]();` to my on() function, but the selected function didn't fire. The function is defined in a script tag in the head. Could I have the selector wrong? – Joe Lowery Nov 28 '14 at 23:26
  • @YuryTarabanko expanded on this idea in his first comment. You need to move your function definitions into an object so that they can be executed in this manner. – Steve0 Nov 28 '14 at 23:36

1 Answers1

1

Create an object that acts as a namespace for your functions. And bind on select change.

$(function() {
   var API = {
     firstFunction: function(){},
     secondFunction: ...
   };

   $('#selectAction').change(function() {
      var method = API[$(this).val()];
      return method && method();
   });
});
Yury Tarabanko
  • 44,270
  • 9
  • 84
  • 98
  • Thanks, Yury, but the function doesn't run as expected. Just to make sure I understand, the value for each array element will always be `function(){}` like `firstFunction: function(){}, secondFunction: function(){}` - is that right? – Joe Lowery Nov 28 '14 at 23:55
  • Nope. The value should be the function you want to be called. :) – Yury Tarabanko Nov 29 '14 at 00:02