By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
459,970 Members | 1,668 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 459,970 IT Pros & Developers. It's quick & easy.

Execute javascript command from variable

P: 63
There is a sequence of ProdCode fields; in this case 1 - 3. I would like to populate the strCBFilter variable with the values contained in those fields using a loop:
Expand|Select|Wrap|Line Numbers
  1. document.frmXRefAttachMaint_01.ProdCode1 
  2. document.frmXRefAttachMaint_01.ProdCode2 
  3. document.frmXRefAttachMaint_01.ProdCode3 
  4.  
The code creates each name by concatenating the number in the loop to the
prefix: document.frmXRefAttachMaint_01.ProdCode". Is there a way to have the program do this:
Expand|Select|Wrap|Line Numbers
  1.   strCBFilter = strCBFilter  +  document.frmXRefAttachMaint_01.ProdCode1 
  2.  
using the value of variable strCBFilterCode which contains:
document.frmXRefAttachMaint_01.ProdCode1 with the number changing each time through the loop.

Full Code:
Expand|Select|Wrap|Line Numbers
  1. for(i = 1; i < 4; i++) 
  2. {
  3.   var strCBFilterCode = "document.frmXRefAttachMaint_01.ProdCode" + i + ".value";
  4.  
  5.    strCBFilter = strCBFilter  +  strCBFilterCode 
  6. }
  7.  
//The highlighted code populates the strCBFilter variable with the contents of the strCBFilterCode variable instead of the field the strCBFilterCode variable refers to. In other languages, I was able to execute commands after placing them in variables. Can this be done in Javascript?//
Feb 19 '09 #1
Share this Question
Share on Google+
7 Replies


Dormilich
Expert Mod 5K+
P: 8,639
I guess you need to pass your strings through the eval() function to get it executed (otherwise it's just a bunch of strings).
Feb 19 '09 #2

P: 63
It worked! Thank you.
Feb 19 '09 #3

Dormilich
Expert Mod 5K+
P: 8,639
I'm glad I could help.
Feb 20 '09 #4

acoder
Expert Mod 15k+
P: 16,027
Instead of eval(), you could use something like:
Expand|Select|Wrap|Line Numbers
  1. document.frmXRefAttachMaint_01.elements["ProdCode" + i].value
Feb 23 '09 #5

P: 63
Thank you. Are there advantages of using this code:

document.frmXRefAttachMaint_01.elements["ProdCode" + i].value

over the eval() function?
Feb 23 '09 #6

acoder
Expert Mod 15k+
P: 16,027
The main benefit here is speed. Using bracket notation (member operators) is much faster - see Note on eval(). You shouldn't get into the habit of bunging everything into eval when there are better alternatives around. You'll notice the benefits when there's more code.
Feb 24 '09 #7

P: 63
Okay, will give it a try and thanks again!
Feb 24 '09 #8

Post your reply

Sign in to post your reply or Sign up for a free account.