0

I don't want to run a big if, else, else, else type statement. I'm basically looking for an excel INDIRECT() equivalent, where I get the string of the id, and call that string as a function, based on which id I'm iterating over. I have inputs with classes that jQuery makes spinners based off of.

$(document).ready(function(){
    var primary = $(".spinnerPrimary");
    var secondary = $(".spinnerSecondary");
    primary.spinner({
        min: 7,
        max: 20,
    });
    primary.spinner("value", 10);
    secondary.spinner({
        min: -4,
        max: 4
    });
    secondary.spinner("value", 0);

When doing max, min, etc. I want to do a spin event that calls a function to update various span containers. I could run one function that just updates every span, or run a big if/else/else case-type statement, so I do have options. What I really want is to pull the id with a this.attr("id"), so that each spinner has a spin set to it based off of the id of that input spinner, that is the same string that corresponds to the name of a defined function.

$(document).ready(function(){
    var primary = $(".spinnerPrimary");
    var secondary = $(".spinnerSecondary");
    primary.spinner({
        min: 7,
        max: 20,
        spin: //fancy code
    });
    primary.spinner("value", 10);
    secondary.spinner({
        min: -4,
        max: 4,
        spin: //same fancy code
    });
    secondary.spinner("value", 0);

    function x() {
        //fancy equation code
    };

    function y() {
        //fancy equation code
    };

In the above example, if the id is "x", then I want it to call function x(), id="y" calls y(), etc. I'm looking for how to do this specific scenario, not how to do it another way (running if/else based on known id's and corresponding function, for example). If the two alternatives I mentioned are the only way to do it, then so be it.

Duplicate of another question: very similar, but also needed help with mapping functions and applying them to spinner. Still new to jQuery, so was a multifaceted(?) question.

1 Answers1

0

Try it this way:

// Setup your functions as a map, so they are easily
// accessible by name.
var fns = {
  x: function(){
    console.log('running x!');
  },
  y: function(){
    console.log('runnning y!');
  }
}

var primary = $(".spinnerPrimary");

primary.spinner = function(options){
  // Tie your `spin` function to the spinner.
  console.log('spinning');
  options.spin();
}
primary.spinner({
    min: 7,
    max: 20,

    // Assign `spin` to one of the `fns` from above
    // using `id` as a key.
    spin: fns[primary.attr('id')] 

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="x" class="spinnerPrimary"></div>
Ezra Chu
  • 832
  • 4
  • 13
  • Awesome, thank you so much! This goes into stuff I'm not as familiar with, so time for more research, but you pointed me in the right direction. Thank you!! – Daniel Padia Jul 22 '17 at 14:27