Reputation: 1257
Trying to understand how to get a set variable string based on the clicked elements id (the variable and id are the same).
var testingid = "testing";
var testingid2 = "testing2";
$('[id ^=inst][id $=STD]').click( function(event) {
event.preventDefault();
var text = this.id; //how do I turn the ID to get the set variable?
console.log(text);
});
So if I click element with id testingid, the console will output "testing".
Upvotes: 0
Views: 36
Reputation: 191976
Instead of separate variables, combine the values to an object, with keys by the names of the id
values. To get the value, pass the id to the object.
Note: you can use a Map instead of an object.
var ids = {
testingid: "testing",
testingid2: "testing2"
};
$('button').click(function(event) {
event.preventDefault();
var text = ids[this.id];
console.log(text);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="testingid">testing</button>
<button id="testingid2">testing2</button>
Upvotes: 1