Amien
Amien

Reputation: 974

w3c document.forms[0].fieldname equivalent

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 <form name="formname"> isn't compliant?

Upvotes: 3

Views: 42264

Answers (5)

Braedon King
Braedon King

Reputation: 55

Would giving the form a name= value and referring to it in the document.forms 'array' by name work?

i.e.: (much abbreviated)

<form name="form1">.insert.your.elements.here.with.name.attribute.set.</form>

and in JS:

document.forms["form1"]["form_item_name"].value;

I'm a rank amateur so if this is wrong, pls leave me a constructive criticism... :-)

Upvotes: 2

Piotr Rochala
Piotr Rochala

Reputation: 7781

The easiest way is to add an id to the input: <input id="fieldname" /> and reference the value from JavaScript like so:

document.getElementById('fieldname').value

or, if you're using jQuery

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

Upvotes: 3

Quentin
Quentin

Reputation: 943999

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

document.forms.formId.elements.field

Upvotes: 6

kennytm
kennytm

Reputation: 523494

(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;

Upvotes: 1

Darin Dimitrov
Darin Dimitrov

Reputation: 1039120

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

var value = document.getElementById('idofelement').value;

Upvotes: 1

Related Questions