tags:

views:

211

answers:

4

I have a form element that I want to address via javascript, but it doesn't like the syntax.

<form name="mycache">
  <input type="hidden" name="cache[m][2]">

I want to be able to say:

document.mycache.cache[m][2]

but obviously I need to indicate that cache[m][2] is the whole name, and not an array reference to cache. Can it be done?

+2  A: 

UPDATE: Actually, I was wrong, you can use [ or ] characters as part of a form elements id and/or name attribute.

Here's some code that proves it:

<html>
<body>

<form id="form1">

<input type='test' id='field[m][2]' name='field[m][2]' value='Chris'/>

<input type='button' value='Test' onclick='showtest();'/>

<script type="text/javascript">
function showtest() {
    var value = document.getElementById("field[m][2]").value;
    alert(value);
}
</script>

</form>

</body>
</html>

Update: You can also use the following to get the value from the form element:

var value = document.forms.form1["field[m][2]"].value;
Chris Pietschmann
That got me going the right direction.... being able to quote the name as a array index is nice.
DGM
The name can include [ and ] characters, but the id may not (even if browsers perform error recovery).
David Dorward
+1  A: 

Is it possible to add an id reference to the form element and use document.getElementById?

FlySwat
+2  A: 

Use document.getElementsByName("input_name") instead. Cross platform too. Win.

Oli
Actually getElementByName is not cross-platform. It's an IE specific thing.
Chris Pietschmann
Actually it is,http://developer.mozilla.org/en/DOM/document.getElementsByNameits just buggy from one browser to the next.
FlySwat
Actually, :), name attribute is only valid for form elements in XHTML, that's why it's buggy! It works fine if you're only using it for input select and textareas
Juan Mendes
+1  A: 

-- and in the old days (in HTML3.2/4.01 transitional/XHTML1.0 transitional DOM-binding) you could use:

form.elements["cache[m][2]"]

-- but the elements-stuff is, as Chris Pietschmann showed, not necessary as these binding-schemes also allow direct access (though I personally would prefer the extra readability !-)

roenving
Well son of a gun. I thought I tried that but could only get numeric entries to work. But sure enough, it works.
DGM
.elements and a lot other element-collections (.images, .frames and so on !-) are exactly collections, so elements is accessible in both ways ...
roenving