0

So what I'm trying to do is convert a series of functions like:

function classAClickSell(){
 if (classASupply>=1) {
  cash = cash + classAValue;
  document.getElementById("cash").innerHTML = cash;
  classASupply = classASupply - 1;
  document.getElementById("classASupply").innerHTML = classASupply;
 };
};

function classBClickSell(){
 if (classBSupply>=1) {
  cash = cash + classBValue;
  document.getElementById("cash").innerHTML = cash;
  classBSupply = classBSupply - 1;
  document.getElementById("classBSupply").innerHTML = classBSupply;
 };
};

and am trying to get them all to resemble something more along the lines of:

function ClickSell(class){
 if (class.concat('Supply') >= 1) {
  cash = cash + class.concat('Value');
  document.getElementById("cash").innerHTML = cash;
  class.concat('Supply')--;
  document.getElementById(class.concat('Supply')).innerHTML = class.concat('Supply');
 }
}

and I was wondering if there is a way to do this, I can't seem to find one. If anyone can help out or point me in the right direction I will be stocked.

2 Answers2

1

Try this code:

function classClickSell(input, node) {
    if (input >= 1) {
        cash += input;
        document.getElementById("cash").innerHTML = cash;
        --input;
        document.getElementById(node).innerHTML = input;
        return input;
    };
};

classClickSell(10, "classASupply");

If classASupply is actually global, and you need a potential decrement to stick after the function call, then you can just assign it to the return value of the above function, i.e.

var classASupply = 10;
classASupply = classClickSell(10, "classASupply");
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
1

You can do something like this to access the variables, assuming the variables are global in scope:

function classClickSell(cls){
    if (window["class" + cls + "Supply"] >= 1) {
        cash = cash + window["class" + cls + "Value"];
        document.getElementById("cash").innerHTML = cash;
        window["class" + cls + "Supply"] = window["class" + cls + "Supply"] - 1;
        document.getElementById("class" + cls + "Supply").innerHTML = window["class" + cls + "Supply"];
    };
};

See #1441532 for other ways you might access those variables.

And don't use class as a variable/parameter name -- it's reserved.

Daniel Centore
  • 3,220
  • 1
  • 18
  • 39