Accessing form elements and how I fell flat on my face
Oh dear, I thought, after something I’d asserted with all the confidence of an infallible man
turned out to be nonsense. In good faith I’ve always tried to encourage
the use of nonproprietary HTML
and client-side scripting. I’m especially hard on my colleagues, who get an earful
if they write proprietary code.
Recently my clever advice came back like a boomerang. I first told someone in a discussion
to use this construct to access form elements.
document.forms("jmeno_formulare").elements("jmeno_prvku")
Does anything look odd, or more precisely proprietary, about it? I certainly didn’t think so. Within
an hour I’d stepped into Wonderland. A colleague and I happened to be reworking a web application,
and because I practice what I preach, I used the construct above. Mozilla had an unpleasant surprise
for me. That bit of code simply couldn’t work.
The syntax above is a proprietary approach that works only in the Internet Explorer family of browsers.
The right approach
If we remember that the form elements will probably be represented in a
collection, we can use these two approaches,
document.forms["jmeno_formulare"].elements["jmeno_prvku"]
or alternatively
document.jmeno_formulare.jmeno_prvku
Another good option is the DOM. We can
give each form element an id attribute and then access the elements
as follows.
document.getElementById("id_formularoveho_prvku");
So there I was preaching water and drinking wine. Once I’d sobered up, I’d proved to myself
again how important it is to test code as well as talk about it.
Related articles
Related CZ Podcast episodes
- #217 · Ivo Lukačovič
On Windy, JavaScript and building companies. · Czech audio
- #3 · Java 6 SE, Vývoj webových aplikací
Dagi and Filemon discuss Java 6 and web application frameworks. · Czech audio