reffering to input names with brackets in them

S

Sandman

Hello! I have a nice little problem :)

I am using PHP to create input fields on a page, and a trick in PHP to have the
result end up in an array is to name the field like "field[foo]".

However, sometimes I need to act on these fields with a javascript, but as far
as I know, you can't do this:

<input type='text' name='field[foo]' />

<script language='javascript'>
document.form.field[foo].value = "bar"
</script>

Since that looks for the foo-entry in the field-array, right?

So how do I refer to the "field[foo]" field in a script?
 
L

lallous

Hello,

Try this:

<body>
<form name='f'>
<input type='button' name='x[]' onclick='accessme(this.form)' value='Hey!'>
</form>
<script>
function accessme(frm)
{
alert(frm.elements['x[]'].value);
}
</script>
</body>
 
R

Randy Webb

Sandman said:
Hello! I have a nice little problem :)

I am using PHP to create input fields on a page, and a trick in PHP to have the
result end up in an array is to name the field like "field[foo]".

However, sometimes I need to act on these fields with a javascript, but as far
as I know, you can't do this:

<input type='text' name='field[foo]' />

<script language='javascript'>

language attribute is deprecated, use type="text/javascript" instead.

Its irrelevant to your problem though.
document.form.field[foo].value = "bar"
</script>

Since that looks for the foo-entry in the field-array, right?

So how do I refer to the "field[foo]" field in a script?


http://www.jibbering.com/faq/#FAQ4_39
 
S

Sandman

Uh, so that means:

document.form["field[]"].value ?

Close:

document.forms['formName'].elements['field[]'].value[/QUOTE]

Aaah, that worked! You actually had to refer to it by the elements[] - I only
thought this was a way to escape names, so if you have an object named 'foo[]'
then you could refer to it by document['foo[]'] - but apprently not. :)

Thanks!
 
R

Randy Webb

Sandman said:
Uh, so that means:

document.form["field[]"].value ?

Close:

document.forms['formName'].elements['field[]'].value


Aaah, that worked! You actually had to refer to it by the elements[] - I only
thought this was a way to escape names, so if you have an object named 'foo[]'
then you could refer to it by document['foo[]'] - but apprently not. :)[/QUOTE]

Glad you got it figured out.

window['foo[]'] will work in some instances, as will document['foo[]']
but using, or attempting to use, that notation, without understanding
its implications/uses will cause you more problems than it will ever
solve. :)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,432
Messages
2,571,682
Members
48,796
Latest member
Greg L.

Latest Threads

Top