-2

I'm trying to create a function that will do the following:

I have some text-boxes and each of them is linked to a variable with a name like:

"textbox1", "textbox2" and so on.

My function needs to change the value of a textbox, when a (change) event is triggered. Depending on where the event happens, I want to change the value of a specific textbox.

In words, my function would do this:

func foo(newVal: string, textboxNumber: number) {

    this.textbox + textboxNumber = newVal;

}

so basically, construct the textbox variable name (ie. textbox1), and the correct number is passed as argument to the function. I just don't know how to construct the name of the variable and make it usable!

I know I could for example use CASES, so for each different case, I would use the correct value:

SWITCH (myCase) {
    case 1 : this.textbox1 = newVal;
}

but the number of textbox is dynamic and growing, so I would like a solution like mine, where I decide in the argument of the function which textbox is going to get updated.

nopassport1
  • 1,821
  • 1
  • 25
  • 53
AJ-
  • 1,638
  • 1
  • 24
  • 49

1 Answers1

1

You can add dynamic object properties using the bracket syntax instead of dot syntax:

function foo(newVal: string, textboxNumber: number) {
  this['textbox' + textboxNumber] = newVal;
}
SparkFountain
  • 2,110
  • 15
  • 35
  • this is working exactly as I needed! thank you – AJ- Jan 27 '20 at 11:01
  • what about this, I pass an object as argument to my function, and the object has multiple property like : value1, value2, value3...and so on. How can I achieve the same as above for this case? Like: ArgumentObject.value[currentNumber] -> where currentNumber will be 1 or 2 or 3 and so on, – AJ- Jan 27 '20 at 12:39
  • That depends on what you like to achieve. Do you want each array value to create a new sub-property, like `[1, 2, 3]` should become `ArgumentObject.value['1']['2']['3']`? – SparkFountain Jan 27 '20 at 12:45