w3c document.forms[0].fieldname equivalent

前端 未结 5 789
眼角桃花
眼角桃花 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 03:59

    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();
    
    0 讨论(0)
  • 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.

    <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;
    
    0 讨论(0)
  • 2021-01-14 04:07

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

    document.forms.formId.elements.field
    
    0 讨论(0)
  • 2021-01-14 04:08

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

    var value = document.getElementById('idofelement').value;
    
    0 讨论(0)
  • 2021-01-14 04:18

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

    0 讨论(0)
提交回复
热议问题