0

I have drop-down list with list of many options. Every time when a user make a choice then specific function starts.

$('#host').on('change', function() {

  if ( $('#host').val() == 'stack' ) stack();
  else if ( $('#host').val() == 'exchange' ) exchange();
  else if ( $('#host').val() == 'something' ) something();
  ...

}

The list become very long because more function will be added. Is there a shorter way to execute name of the function from $('#host').val()?

Lucas
  • 2,924
  • 8
  • 27
  • 32

3 Answers3

1

Try to call it from the window's object,

$('#host').on('change', function() {
  window[this.value]();
});
Rajaprabhu Aravindasamy
  • 66,513
  • 17
  • 101
  • 130
  • Ok, finally I found working solution. I needed to use `eval($('#host').val() + "();");` – Lucas Jul 04 '14 at 13:59
0

Take a look at this demo: JSFIDDLE

JS code:

$(document).ready(function(){
    function stack()
    {
        alert('Called function stack');
    }
    function exchange()
    {
        alert('Called function exchange');
    }
    function something()
    {
        alert('Called function something');
    }
    $('#host').on('change', function() {

      if ( $('#host').val() == 'stack' ) stack();
      else if ( $('#host').val() == 'exchange' ) exchange();
      else if ( $('#host').val() == 'something' ) something();
    });
});

HTML:

<select id="host">
    <option value="">Select value</option>
    <option value="stack">stack</option>
    <option value="exchange">exchange</option>
    <option value="something">something</option>
</select>
Rahul Gupta
  • 9,775
  • 7
  • 56
  • 69
0

I found an answer in different question, so the only way that works for me is:

eval($('#host').val() + "();");
Lucas
  • 2,924
  • 8
  • 27
  • 32