views:

150

answers:

4

I've been using

document.forms[0].fieldname.value

to get values in javascript from a form, but I'd like to use a name to reference the field and not a 0, what would be the equivalent these days since isn't compliant?

+1  A: 

Giving each element an unique id and using this id with the getElementById function is recommended:

var value = document.getElementById('idofelement').value;
Darin Dimitrov
+2  A: 

According to http://www.w3.org/TR/html401/interact/forms.html we shouldn't use name attribute on input elements, we should use id instead, so the correct JavaScript is:

document.getElementById('fieldname').value;

or

$('#fieldname').val();

(if we're using jQuery)

rochal
+1  A: 

(document.forms is still supported. You can keep it.)

The best way to to give the field an id and use document.getElementById.

<input type="text" name="fooName" id="fooId" />
...
document.getElementById("fooId").value;

If you can't add an id, you can still use document.getElementsByName, but it will return an array instead of a single element because many may share the same name.

document.getElementsByName("fooName")[0].value;
KennyTM
A: 

The forms collection is standard DOM 1, there is nothing wrong with using it.

document.forms.formId.elements.field
David Dorward