Oskar Sjödin
Oskar Sjödin

Reputation: 3

JavaScript, How can I parse a variable into a command?

What I'm trying to do is to enable multiple checkboxes within for(). Right now it looks like this, but from what I have learned, you can't run the command from a variable like this, I can't run, (e.g) cab_type_value = "whatever". Nor can I run road_load_enabled; it just doesn't work. Does anyone how I can achieve this? How can I parse my var J in the document.MyForm.InputName.disabled?

for( var j=1; j<=14; j++ ) {
    var cab_type_value = "document.exe_mode_form.cab_type" + j + ".value";
    var cab_type_checked = "document.exe_mode_form.cab_type" + j + ".checked == 1";

    for( var i=1; i<=document.exe_mode_form.road_load_number.value; i++ ) {
        var road_load_value = "document.exe_mode_form.load" + i + ".value";
        var road_load_enabled = "document.exe_mode_form.load" + i + ".disabled = false";
        var road_load_disabled = "document.exe_mode_form.load" + i + ".disabled = true";
        var rld_db = "document.exe_mode_form.a" + i + "_a1.value";

        if ( cab_type_checked ) {
            if ( test == 1 ) {
                if(road_load_disabled) {
                    alert("road_load_disabled");
                    road_load_enabled;
                }
                test = 2;
            }

            if(cab_type_value == rld_db) {
                if(olof == 1) {
                    alert("cab_type_value  == rld_db");
                    olof = 2;
                }

                road_load_enabled;
            }
        }
    }
}

Also, this part isn't working:

if(cab_type_value == rld_db) {
    if(olof == 1){
        alert("cab_type_value  == rld_db");
        olof = 2;
    }

    road_load_enabled;
}

And I have checked, cab_type_value has the same value as rld_db.

Upvotes: 0

Views: 1148

Answers (1)

Elias Van Ootegem
Elias Van Ootegem

Reputation: 76413

try changing these kind of lines:

var cab_type_value = "document.exe_mode_form.cab_type" + j + ".value";

to:

var cab_type_value = document.exe_mode_form['cab_type' + j].value;

The same logic holds for function calls:

someVariable = 'alert';
window[someVariable]('Foo!');//alerts foo

If your function is not declared in the global scope, you can replace window with any namespace object: foobarObject.orEven.nestedOnes[someVariable]();
And finally, because I personally loathe the window keyword (it's a circular reference), you can simply choose to use this['alert']('foo'); in a regular function call or in the global scope. this points to its called context, which in these cases is the global object

Upvotes: 1

Related Questions