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

6
  • 1
    Put those functions into object {name: func, name2: func2}[nameToBeCalled]() Commented Nov 28, 2014 at 23:09
  • Is this what you are asking about? stackoverflow.com/a/3326095/903014 Commented Nov 28, 2014 at 23:09
  • @YuryTarabanko - I'm sorry, I don't know what you mean. Can you clarify? Commented Nov 28, 2014 at 23:20
  • Create an object: var API = {firstFunction: firstFunction, ...}. And use it like this: $('#selectAction').change(function(){API[$(this).val()]();}) Commented Nov 28, 2014 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? Commented Nov 28, 2014 at 23:26

1 Answer 1

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();
   });
});
Sign up to request clarification or add additional context in comments.

2 Comments

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?
Nope. The value should be the function you want to be called. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.