steve Kim steve Kim - 4 months ago 9
jQuery Question

JS variable name

I have simple js variables:

var check_first = 0;
var check_second = 1;


Then,
<div class="chosen" data-type ='first'>


I have a function to get the data attribute:

$(document).on('click', '.chosen', function (e) {
var type = $(this).data('type');
});


When the
.chosen
is clicked, I get the
type
variable with the value of "
first
"

Then I want to use this value to identify one of the two variables at the top and get the value of 0:

For example:

var chosen = check_ + type; //of course wrong, and should give "check_first" when properly written.
console.log(chosen); //giving 0 as the result


How can I achieve this?

Answer

Your best chance is to use a simple key-value object to achieve this:

var check = {
    first: 0,
    second: 1
};

$(document).on('click', '.chosen', function (e) {
    var type = $(this).data('type');
    console.log(check[type]);
});