0

I'm trying to change different variables based on what button a user has clicked. For example, I have three buttons:

<button id="button1" onclick="isClicked(this.id)">B1</button>
<button id="button2" onclick="isClicked(this.id)">B2</button>
<button id="button3" onclick="isClicked(this.id)">B3</button>

3 objects:

var button1 = { someValue: 0, otherValue: 5 };
var button2 = { someValue: 0, otherValue: 5 };
var button3 = { someValue: 0, otherValue: 5 };

And the ID of the button that is clicked is passed into the JavaScript like so

function isClicked(clicked_id) {
    selectedID = (clicked_id);
}

What I am trying to achieve is for a value to be applied to a variable based on the button that is clicked - so if button1 is clicked, the button1 object is changed, but if button2 is clicked, the button2 object is changed.

I have looked at Programmatically setting the name of a variable and Programmatically set variable names by appending an ID parameter but I cannot see how they would work in my situation.

Is there an efficient way to do this?

Community
  • 1
  • 1

1 Answers1

1

Nest your objects:

var buttons = {
    button1 : { someValue: 0, otherValue: 5 },
    button2 : { someValue: 0, otherValue: 5 },
    button3 : { someValue: 0, otherValue: 5 }
};

Now:

function isClicked(clicked_id) {
    var theClickedButtonObject = buttons[clicked_id];
    // do something
}
Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592