w3c document.forms[0].fieldname equivalent

前端 未结 5 838
眼角桃花
眼角桃花 2021-01-14 03:35

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

5条回答
  •  灰色年华
    2021-01-14 04:02

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

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

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

提交回复
热议问题