user1837608
user1837608

Reputation: 960

Better way to assign variables?

In my project, I have 20-30 user input values that are assigned to variables. Each input has an id that I have tried to structure in a smart way. But I'm new to coding so I have been writing out each variable assignment in order. This is not a neat way to do it, but I'm not sure how to structure a for loop to fit the bill.

My vars are structured as such:

    var box_1 = $("#box1").val();
    var box_1_2 = $("#box1_2").val();
    var box_2 = $("#box2").val();
    var box_2_2 = $("#box2_2").val();
    var box_3 = $("#box3").val();
    var box_4 = $("#box4").val();
    var box_4_2 = $("#box4_2").val();
    var box_5 = $("#box5").val();
    var box_5_2 = $("#box5_2").val();
    var box_6 = $("#box6").val();
    var box_7 = $("#box7").val();
    var box_8 = $("#box8").val();
    var box_9 = $("#box9").val();
    var box_9_2 = $("#box9_2").val();
    var box_9_3 = $("#box9_3").val();
    var box_9_4 = $("#box9_4").val();
    etc...

Any help is very much appreciated!

EDITED TO ADDRESS SOME COMMENTS

To answer the question in the comment: The ids are randomly named boxn and variables box_n, for ease of writing.
The ids refer to a mixture of selectboxes, input fields and radio buttons.
Every box_n is always assigned to boxn.
Some boxn will be followed by boxn_a, boxn_b, boxn_c because these are part of related input fields.

Now why this? The end user moves through each field, changes the options or enters text to suit their need, and the end result is text generated using the vars. Kind of like a mad lib generator.

Upvotes: 1

Views: 71

Answers (1)

DGS
DGS

Reputation: 6025

Method 1

You could use multidimensional arrays Example Fiddle

var box_counts = [2, 2, 1, 2, 2, 1, 1, 1, 4];
var box_vars = [];

for (var i = 0; i < box_counts.length; i++) {
    box_vars[i] = [];
    box_vars[i][0] = $('#box' + (i + 1)).val();
    for (var j = 1; j < box_counts[i]; j++) {
        box_vars[i][j] = $('#box' + (i + 1) + '_' + (j + 1)).val();
    }
}

Example use: box_vars[0][1] refers to the value of your current box_1_2 variable, box_vars[8][3] refers to your box_9_4 variable. Note that since the arrays are 0 indexed while you are using 1 indexed names you will have to do a bit of mental arithmetic or change the structure to have an empty 0 index

Method 2

Alternatively you can make the variables window attributes Example Fiddle

$('[id^=box]').each(function(){
    window[this.id.replace('box', 'box_')] = $(this).val()
})

which would allow you to call them how you do now. They will be global however.

Example use: box_1_2 will refer to $("#box1_2").val(); and box_9_4 will refer to $("#box9_4").val(); like you would expect with your current system

Upvotes: 1

Related Questions