views:

47

answers:

2

This is my JavaScript code:

<script>
function change(name){
    var element = document.all.name.value;
}
</script>

It returns an error. How to pass to the function the element's name in order to change its value?

+7  A: 

For a quick fix:

var element = document.all[name].value;

But keep in mind this gets the value, not the element itself. To get the element, then change the value, do:

var element = document.all[name];
element.value = 'whee';

Also, you should consider using another way to access the elements instead of document.all. Look into using IDs instead of names with the document.getElementById() function. See this JavaScript best practices list.

As Peter Bailey points out in his answer, many HTML elements can have the same name. This is one reason why document.getElementById() is preferable: element IDs are unique (in valid HTML, of course).

Cameron
Good answer. I would recommend using ID. Then you can do document.getElementById(id); Much more reliable
Zoidberg
@Zoidberg: Yep, was integrating that into my answer as you commented :-)
Cameron
@Cameron Awesome :D
Zoidberg
+2  A: 

If by "name" you mean "name attribute", you have to understand that names are not unique to an HTML document. They need context.

Although you can use document.all - that is non-standard and only works in IE. You'll be better off using a more cross-browser friendly mechanism.

Typically, name attributes will belong to elements in a form, such as <input/> and <select> elements. The names of these elements are exposed as properties of the <form>'s elements property in the DOM.

If you can get access to the form's DOM object, then you can access its elements' DOM objects too.

An example

<form id="foo">
  <input type="text" name="test" />
</form>

<span onclick="change( 'foo', 'test' );">Change Value</span>

<script type="text/javascript">

function change( formId, elementName )
{
  // Get the form's DOM object
  var f = document.getElementById( formId );

  // Get the element's DOM object
  var element = f.elements[elementName];

  // Modify the element's value property
  element.value = 'Hello World';

  // Note, the above 3 lines can be refactored to this
  // document.getElementById( formId ).elements[elementName].value = 'Hello World';
}

</script>
Peter Bailey
`document.all` also works in Opera, but I agree it still shouldn't be used if at all possible (which is almost always the case).
Cameron