tags:

views:

891

answers:

2

Hello

A basic question I assume for someone who does JS on a daily basis. I'm helping a friend that does not use the recent sweets (JQuery, prototype and co.).

How should I get a reference to a document element by name ?

I would like to allow a selection user does in a <SELECT /> element modify the value of an <INPUT /> element.

Both elements don't have ID fields defined, only names.

This should be portably obviously (Mozilla, IE, Opera).

Thank you.

+2  A: 

You could use getElementsByName function which will return an array of all elements having a given name:

var elements = document.getElementsByName('some_name');
Darin Dimitrov
Thank you, was doing getElementByName. Note the missing (s).
Maxim Veksler
Personally I prefer $("some_name") :-)
cletus
@cletus: *That's* convenient! When did it get included in vanilla JavaScript? ;-)
Tomalak
@cletus: that's not event included in the recent sweets!
Crescent Fresh
Since when do we start letting such minor issues as that prevent us from bigging up jQuery huh?
bobince
Note: IE is still buggy on this returning elements with a matching ID attribute. (it won't affect the poster, but one should be aware of this bug)
scunliffe
A: 

If <input> and <select> are members of the same <form> element, you can reference the fields directly, they are members of the form object:

<form>
  <select name="bar" onchange="this.form.foo.value = this.value;">
    <option value="1">Option 1</option>
    <option value="2">Option 2</option>
    <option value="3">Option 3</option>
  </select>
  <input type="text" name="foo">
</form>

You can wrap it in a function, of course.

Tomalak