Search code examples
javascriptstringvariablesvalue-of

How to detect name of another variable but not his value javascript?


In the js code I have

var a1 = "text in a1";
var right_text = a1;

a1 is the variable where this text is written. the value of right_text will change. I need have more variables like a1 because each of them will do something else.

  switch (right_text) {
     case a1:
...
     case a2:
...
     case a3:
...

I would like it to increase value of right_text to a2 after first click on the button and to a3 after another click and so on. So I want to get the variable a1 as a string, add one and get a2.

But now I need to somehow detect the current value of right_text, ie a1, not the content written in a1.

I tried

right_text.toString (); 

But that will return the mentioned content a1. It could be done somehow so that I can get value of right_text (a1 in this case) and convert it as string? Thank you


Solution

  • Assuming that right_text is a current step var. You can set base value for right_text and a counter.

    var right_text = 'a';
    var step_counter = 0;
    

    When the user click on your button, increase a counter.

    step_counter++;
    

    Now, you can set the current step text :

    right_text = 'a' + step_counter;
    

    When you display right_text, your output will be like that :

    '' => 0 clicks
    'a1' => First click
    'a2' => Second click
    

    var right_text = '';
    var step_counter = 0;
    
    function countMe() {
      step_counter++;
      right_text = 'a' + step_counter;
      document.getElementById( 'currentVal' ).innerHTML = right_text;
    }
    <button onclick="countMe();"> Click Me ! </button><br/>
    <p id='resultText'>
      Current Value : <span id="currentVal"></span>
    </p>