0

I use the following in perl to create dynamic variables $$x = "color"; This will allow me to access the variable as $color. I want to do something similar in JavaScript. I want to create dynamic variable names in JavaScript that come from an unknown HTML FORM of key value pairs. In other words lets say I read in name/value pairs looping through document.forms['1'] with values of pagetitle=fishing, phone=555-5555, and color=red. I want create JavaScript variable names of pagetitle, phone, and color so I can perform in-place html updates, following a successful db update, using something like so

var f = document.forms[1];
for ( var i = 0; i < form.elements.length; i++ ) {
      var e = f.elements[i];
      e.name = e.value);   /* something like $$e.name = e.value in PERL */ 
}

document.getElementById('pagetitle').innerHTML = pagetitle;
document.getElementById('phone').innerHTML = phone;
document.getElementById('field1').style.background = color;
document.getElementById('field2').style.background = color;

It's the e.name and e.value area that I don't know how to make into a dynamic variable?

I know I could just do something like so...

document.getElementById('pagetitle').innerHTML = document.forms[1]['pagetitle'].value;

but I would still like to know how to work with dynamic variables in JavaScript.

ikegami
  • 367,544
  • 15
  • 269
  • 518
Airman
  • 130
  • 2
  • 10
  • 2
    please have a look here: http://stackoverflow.com/questions/5117127/use-dynamic-variable-names-in-javascript – Nina Scholz Feb 10 '17 at 21:19
  • Doing this in Perl is a great way to shoot yourself in the foot. In Javascript it's not any better. Use a hash or an object in Javascript. – simbabque Feb 10 '17 at 21:20
  • `$$x = "color";` It's almost like you took your example straight out of the [canonical post](http://perl.plover.com/varvarname.html) about why you shouldn't do exactly what you're talking about. – ThisSuitIsBlackNot Feb 10 '17 at 21:22
  • Thanks for the reference. That helps. I wasn't able to find the right one. I use it server side in Perl to create name/value pairs and works great. I know it could be risky if not careful. – Airman Feb 10 '17 at 21:28

0 Answers0