jquery call a variable based off other variables

Report
Question

Please briefly explain why you feel this question should be reported .

Report Cancel

I have these variable defined:

var Counter1_1_yes = 0;
    var Counter1_2_yes = 0;
    var Counter1_3_yes = 0;
    var Counter1_4_yes = 0;
    var Counter1_5_yes = 0;
    var Counter1_6_yes = 0;
    var Counter1_7_yes = 0;

and I have this $.each statement inside an ajax call:

$.ajax({
        type: "GET",
        url: "/api/action/getAnswers?bullShitString=bullShitString",
        dataType: 'json',
        cache: false,
        success: function (data) {

            $.each(data, function (key, value) {

                Counter + value.questionnaireID + "_" + value.questionID + "_" + value.answer++;

                console.log(Counter1_1_yes);

            });


        }
    });

what I am trying to do, is in my each statement take the results from the ajax and add 1 to the variable.

I just get this error saying Counter is undefined. Is what I am trying to do possible?

Please Help.

solved 0
1 Answer 4 views 0

Answer ( 1 )

    4
    November 13, 2016 at 11:45 am

    Please briefly explain why you feel this answer should be reported .

    Report Cancel

    The variable names can’t be dynamic. For this purpose, I’d advice the object.

    var Counter = {
        "1_1_yes":0,
        "1_2_yes":0,
        "1_3_yes":0,
        "1_4_yes":0,
        "1_5_yes":0,
        "1_6_yes":0,
        "1_7_yes":0
    }
    
    ...
    
    Counter[value.questionnaireID + "_" + value.questionID + "_" + value.answer]++;
    console.log(Counter['1_1_yes']);
    
    Best answer

Leave an answer

Browse

What is the capital of Egypt ? ( Cairo )

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>