Search code examples
javascriptformsw3c

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?


Solution

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