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 f
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();
(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;
The forms collection is standard DOM 1, there is nothing wrong with using it.
document.forms.formId.elements.field
Giving each element an unique id and using this id with the getElementById function is recommended:
var value = document.getElementById('idofelement').value;
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... :-)