jquery trigger function based on select list

433 views Asked by At

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

1

There are 1 answers

2
Yury Tarabanko On BEST ANSWER

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();
   });
});