0

This is a sample from my java script code. With this code I get a correct result (1, 2). Now, instead variable "james" I want to set a variable depending on input value (var input in this case). How can I do that? Is there a way to find JavaScript variable on the page via input value?

 var james = "James", 
     daniel = "Daniel",
     jacob = "Jacob";

 // some code //

 var james = [1, 2],
     daniel = [3],
     jacob = [4, 5];

 function buttonclick()
 {
    var input = document.getElementById("selector").value;
    var text2 = "";
    var y;
    for (y in james) {

        text2 += james[y] + "<br>"; 
        }
    document.getElementById("demo").innerHTML = text2;
 }

2 Answers 2

2

You can pick them up through the window global object:

 var james = "James", 
     daniel = "Daniel",
     jacob = "Jacob";

 // some code //

 var james = [1, 2],
     daniel = [3],
     jacob = [4, 5];

 function buttonclick()
 {
    var input = document.getElementById("selector").value;
    var text2 = "";
    //input could be james, daniel or jacob
    var y;
    for (y in window[input]) {

        text2 += window[input][y] + "<br>"; 
        }
    document.getElementById("demo").innerHTML = text2;
 }

Unless they are in a closure or nested in some function.

Sign up to request clarification or add additional context in comments.

1 Comment

Yes, it works! Just in for loop, instead of james[y] , I suppose you meant (window[textruta])[y]
0

The same like it is done with var input in your example. But I guess you're asking to make the variable when someone actually puts something in into the input? Then you need to make a function which listens for example to the onKeyUp event of the input field and then saves the current value into the variable.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.