[X]

Reaching Fields With eval

browser tricks 1997 partly

Numbered form fields read with eval, because bracket notation had not reached the tutorials.

In 2026: Partly, and this page cannot even run the old half: eval('document.f.field' + i) still works on a page with no Content Security Policy, but this site sets one with no unsafe-eval, so the demo's eval is refused and says so. The bracket notation that replaced it, document.f['field' + i], needs no eval and no permission, which is the whole lesson.

Where it came from: The free script archives, roughly 1997 to 2002. Bracket notation was in JavaScript from the start; the tutorials taught eval anyway.
MDN eval MDN CSP

<form name="f">
  <input type="text" name="field0" value="one" size="6">
  <input type="text" name="field1" value="two" size="6">
  <input type="text" name="field2" value="three" size="6">
</form>
<p id="out" style="font:13px Verdana"></p>

<script language="JavaScript">
var out = [];
try {
  // The 1997 way. Tutorials taught this for years.
  out.push("eval says: " + eval("document.f.field1.value"));
} catch (e) {
  out.push("eval is refused on this page (Content Security Policy): " + e.name);
}
// The way that was always there.
var joined = [];
for (var i = 0; i < 3; i++) joined.push(document.f["field" + i].value);
out.push("bracket notation says: " + joined.join(", "));
document.getElementById("out").innerHTML = out.join("<br>");
</script>
sandboxed demo · breaks nothing but itselfrestart

More in browser tricks

all 30 in browser tricks › · the whole library ›