Ken
Ken

Reputation: 15

Run multiple Javascript functions from drop-down onchange menu

Let's say I have different JS functions...

function stores(NY)
{
blah, blah, blah...
}
function stores(CA)
{
blah, blah, blah...
}
function stores(FL)
{
blah, blah, blah...
}

And I wish to run them from this drop-down menu...

<select onchange="stores(this.value);">
<option>Please select your state from this list...</option>
<option value="NY">New York</option>
<option value="CA">California</option>
<option value="FL">Florida</option>
</select>

And so on up to 50 US States, that's why I need a simple way to call these functions but this is not working. Any ideas will be much appreciated. Thank y'all in advanced!

Upvotes: 0

Views: 1997

Answers (3)

David G
David G

Reputation: 96800

The simplest way would be to create an object literal whose keys in their key-value pairs are the names by which to call the functions.

var methods = {
    "NY": function() {},
    "CA": function() {},
    "FL": function() {}
};

element.onchange = function() {
    methods[ this[ this.selectedIndex ].value ]();
};

This concept gets rid of if and case statements and is object-oriented. We programmatically issue the event handler and call the function based on the value of the element's selected index.

Upvotes: 2

Database_Query
Database_Query

Reputation: 634

you can do this by switch case

function stores(city) {

switch(city){
 case 'NY':
    //your stuf
    break;
  case 'CA':
    //your stuf
   break;
  case 'FL':
    //your stuf
   break;
 default:
   code to be executed if n is different from above all case
  }

}

Upvotes: 0

xdazz
xdazz

Reputation: 160833

You just need one function.

function stores(city) {
  if (city === 'NY') {
    //blah, blah, blah...
  } else if (city === 'CA') {
    //blah, blah, blah...
  } else if (...) {
    // ... and so on
  }
  // ...
}

Upvotes: 0

Related Questions