w3c document.forms[0].fieldname equivalent

浪子不回头ぞ 提交于 2019-12-01 05:49:06

问题


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?


回答1:


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



回答2:


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

document.forms.formId.elements.field



回答3:


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... :-)




回答4:


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

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



回答5:


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


来源:https://stackoverflow.com/questions/2810573/w3c-document-forms0-fieldname-equivalent

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!