User Tools

Site Tools


JavaScript: Dynamic Form Element Names

This article was originally published on September 7, 2008.

Purdue, like a lot of enterprise-level organizations, uses LDAP to manage certain things. One of the advantages to LDAP is that it can provide information about users on a domain. Our organization uses some globally-accessible ColdFusion functions to quickly get user information based on user ID data.

With AJAX libraries and frameworks (we use Scriptaculous and Prototype), we’ve also created a bit of JavaScript that allows retrieving the first and last name of a user from an entered ID without having to submit the form and post back to the page. It’s a useful tool, but it was originally written to only work with one text field on a page.

In one of the applications I’m currently working on, I have several different fields that require this behavior. I decided to modify the script we have so that I could pass a value to the function as a sort of prefix. That way, I could have a text box with an ID of OwnerID, and another with an ID of UserID. Instead of the normal script, which is called just by lookupID(), I’d be able to refer to a specific input, using something like lookupID('Owner').

Everything was coming along the way I needed it to, until I got to the section of code that dealt with changing the values of input boxes on the form. When a user enters a person’s ID, the JavaScript code looks up the person’s first and last name and displays that name in a read-only input box on the page. Since each ID input box had a corresponding read-only input box, I needed to be able to dynamically refer to that box using the prefix passed to the function.

It’s very easy to accomplish, but it took a bit of Googling to figure it out. It turns out that square brackets give us the ability to manage the task. For instance, for a form named “edit”, the standard code might look something like this:

form.edit.OwnerName.value = '(' + FirstName + ' ' + LastName + ')';

However, the OwnerName input box ID needs to be different for each read-only box, so we use square brackets to create a dynamic form element reference, where foo is the prefix passed to the function:

form.edit.elements[foo + 'Name'].value  = '(' + FirstName + ' ' + LastName + ')';

It’s a bit more complicated than dynamic variable names in ColdFusion, but it’s fairly easy to implement, and it gets the job done.

Dynamic variable names can be extremely useful when dealing with similar pieces of code, loops and other such concepts. Each language deals with it differently, but I’ve found it an important element to learn about in most of the applications I create.