Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic variables names in javascript

I have variable:

var variableDynamic = 1;
// or    
var variableDynamic = 1 + i++;

Is there any way to use that to create dynamic variable names, for example something like this:

var variableName + variableDynamic = {};
// or
var (variableName + variableDynamic) = {};

I know what I wrote above is absurd, but this is to explain the idea. Is it possible?


Ok, what I want to do to create element (upload form) every time user click on add new file group, everything is working fine except that plugin that I use for it need special variable for each upload form to trigger upload button (.uploadStoredFiles();).

This is rough code I did:

    $('#addOneMoreFileOrGroup').on('click', function(){

    var latestFileUploaderId = parseInt($('.well-large .file-uploader').last().attr('id').split('-')[2]) + 1;

    $('.well-large .control-group:last').after('<div class="control-group deal-type-online">  \
        <label class="control-label">File / File Group Title:</label> \
        <div class="controls"> \
            <input class="span4 file-title" type="text"> \
            <span class="question label label-warning" data-title="File / Group Name:" data-content="Name for your file or group of related files (for example your brand logotype in different file formats)." data-original-title="">?</span> \
            <div id="file-uploader-' + latestFileUploaderId + '" class="file-uploader"></div> \
        </div> \
    </div>');

    var HERE_I_NEED_DYNAMIC_VAR = new qq.FileUploader({
        element: document.getElementById('file-uploader-' + latestFileUploaderId + ''),
        action: 'do-nothing.htm',
        autoUpload: false,
        debug: true,
        uploadButtonText: '<i class="icon icon-plus"></i> Select Files...',
        onSubmit: function() {

            $('#file-uploader-' + latestFileUploaderId + ' .qq-uploader').after('<button id="file-uploader-trigger-' + latestFileUploaderId + '" class="btn btn-primary"><i class="icon-upload icon-white"></i> Upload now</button>');

            $('#file-uploader-trigger-' + latestFileUploaderId + '').on('click', function() {

                if($(this).parent().parent().parent().parent().find('.file-title').val() !== '') {
                    HERE_I_NEED_DYNAMIC_VAR.uploadStoredFiles();
                } else {

                    $(this).parent().parent().parent().addClass('error');

                }

            });

        }
    });

});

}
like image 879
ignaty Avatar asked Nov 08 '12 15:11

ignaty


People also ask

How do you create a dynamic variable name?

Use an Array of Variables The simplest JavaScript method to create the dynamic variables is to create an array. In JavaScript, we can define the dynamic array without defining its length and use it as Map. We can map the value with the key using an array and also access the value using a key.

What is a dynamic variable example?

Dynamic Variable Overview The distinguishing characteristic of a dynamic variable is that its value can change while the application runs. For example, your application might maintain a threshold value that is compared to a field value in each tuple processed.

What is a dynamic variable?

In programming, a dynamic variable is a variable whose address is determined when the program is run. In contrast, a static variable has memory reserved for it at compilation time.

How to create a dynamic variable name in JavaScript?

In JavaScript, dynamic variable names can be achieved by using 2 methods/ways given below. eval (): The eval () function evaluates JavaScript code represented as a string in the parameter. A string is passed as a parameter to eval ().

How to use dynamic variable names in Python?

One of the most common ways of using dynamic variable names is via eval function, which evaluates any expression and returns its result. Let us say you have the following variable. Next, let us say you create another variable b.

How to implement the creation of dynamic variable names using eval () function?

Inside eval (), we pass a string in which variable valuei is declared and assigned a value of i for each iteration. The eval () function executes this and creates the variable with the assigned values. The code is given below implements the creation of dynamic variable names using eval ().

What are dynamic variables in C++?

Dynamic variables are those types of variables that don’t have any specific name in the code through hard coded. A dynamic variable name is auto-generated while running the program.


3 Answers

In JavaScript, an object's properties can be access either by obj.prop or obj['prop'].

In the global scope, all variables are children of the window property. So you'll be able to do:

var variableDynamic = 'Test';
window['variableName' + variableDynamic] = 'your value';

Check out this fiddle.

However, if you'd like to limit the scope of this variable to a function, you would have to define a parent object and use this in place of window.

like image 198
Connell Avatar answered Oct 08 '22 19:10

Connell


You can create dynamic variables with eval.

eval("dynamic" + i + " = val[i]");

Also have a look at this: Use dynamic variable names in JavaScript

like image 23
sainiuc Avatar answered Oct 08 '22 19:10

sainiuc


To add to FAngels answer, you may use bracket notation anywhere. This means that in addition to using window['var'], you can use this['var'].

like image 5
Awesomeness01 Avatar answered Oct 08 '22 21:10

Awesomeness01