Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 762
  • Last Modified:

How to eval() dynamic object name with '-' in its name

Hello,
i use a form with a lot of checkboxes, which are generated dynamically. Every checkbox has its ID which comes from a database. These IDs can be positive or negative. Thus a checkbox can have a name like "mybox-2".
Sadly my JavaScript function has a problem with such names...
How can i tell the eval() function to evaluate '"document.formWithCheckboxes.mybox" + boxID' as a String for negative boxIDs, too?

Thanks in advance!
function swapAll(boxID) {
            box = eval("document.formWithCheckboxes.mybox" + boxID);
            box.checked = !box.checked;
}

Open in new window

0
sumawuscha
Asked:
sumawuscha
  • 3
  • 2
2 Solutions
 
b0lsc0ttCommented:
sumawuscha,

Try ...

box = eval("document.formWithCheckboxes.elements[mybox" + boxID + "]");

Let me know if you have any questions or need more information.

b0lsc0tt
0
 
Göran AnderssonCommented:
Don't use eval at all:

box = document.formWithCheckboxes.elements('mybox' + boxID);
0
 
b0lsc0ttCommented:
You will need to use square brackets with elements.  For example ...

box = document.formWithCheckboxes.elements['mybox' + boxID];

Thanks for the grade, the points and the fun question.

bol
0
 
Göran AnderssonCommented:
Right... I was looking at the Microsoft documentation, which specifies parentheses...
0
 
b0lsc0ttCommented:
@GreenGhost - I have made the same mistake at least a few times as I switch from ASP/vbscript to Javascript and back.  The MS document probably was using clientside vbscript which needs parentheses.  Good suggestion to lose the eval() though unless it is needed for some reason we can't see. :)

bol
0

Featured Post

Vote for the Most Valuable Expert

It’s time to recognize experts that go above and beyond with helpful solutions and engagement on site. Choose from the top experts in the Hall of Fame or on the right rail of your favorite topic page. Look for the blue “Nominate” button on their profile to vote.

  • 3
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now