Rhecil Codes Rhecil Codes - 1 year ago 63
jQuery Question

How do I pass variables to a function based on select value?

For the sake of this question, this is a simplified version of the problem I am having.

If I have a

in my HTML:

<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>

Then my JS:

var a,b = 12;
var c1,d1,e1,
c6,d6,e6 = // Assigned individually from loop. NOT actual code.

function myFunction(a,b,c,d,e){
// do something with a,b,c,d,e

$('select').on('change', function() {
var id = $(this).val();
c = c+id;
d = d+id;
e = e+id;
myFunction(a, b, c, d, e);

In the above code, if I select option 3, I want to pass the function variables c3, d3, e3.

How do I assign the '3' from the id to the variables passed? What is wrong with the select portion this code?

Please help. Thanks.

Answer Source

Consider a more sensible data structure instead of all those individual variables. Start with an object:

  c: '',
  d: '',
  e: ''

After all, if c, d, and e should be interpreted together in some way and represent something that's connected, then that sounds like an object you're trying to describe.

Then just have an array of that object:

var myObjects = [
    { c: '', d: '', e: '' },
    { c: '', d: '', e: '' },
    { c: '', d: '', e: '' },
    // etc.

This would conform more to what your comment suggests:

// values assigned dynamically from loop

Then what your option values would contain is simply the index of the element you're looking for:

  <option value="0">1</option>
  <option value="1">2</option>
  <option value="2">3</option>
  <option value="3">4</option>
  <option value="4">5</option>
  <option value="5">6</option>

And you can get the element based on that index:

var id = $(this).val();
var myObject = myObjects[id];
myFunction(a, b, myObject.c, myObject.d, myObject.e);

There's probably more that can be done to improve things here, but the contrived nature of the example makes it semantically vague. The point here is to put the logic into the structures you're using, rather than have complex logic to account for the lack of structures.

"Smart data structures and dumb code works a lot better than the other way around."
- Eric S. Raymond, "The Cathedral and the Bazaar"

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download