0

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!

1
  • Please choose a best answer by clicking the checkmark next to it. Thanks. Commented Sep 30, 2012 at 16:19

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

This would be a good way so long as the logic is different in the functions. If the logic is the same but the data is different then the shared logic should be consolidated and object could represent the data difference.
The logic will be different because he wanted separate functions for each of them. If the value of the selected index doesn't make a difference, then he wouldn't have made different functions for each of them. But that's only assuming the OP knows what he's doing.
It's impossible to say without any of the function body shown, but from the name of the function it looks like they may only vary by the data returned. My comment was directed to the OP for that case, not as a critique on the answer.
0

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
  }
  // ...
}

Comments

0

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
  }

}

Comments

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.