JavaScript get element by name

Juliver Galleto picture Juliver Galleto · Apr 24, 2012 · Viewed 400.4k times · Source

Consider this function:

function validate()
{
  var acc = document.getElementsByName('acc').value;
  var pass = document.getElementsByName('pass').value;

  alert (acc);
}

And this HTML part:

<table border="0" cellpadding="2" cellspacing="0" valign="top">
    <tr>
        <td class="td1">Account</td>
        <td class="td2"><input type="text" name="acc" /></td>
    </tr>
    <tr class="td1">
        <td>Password</td>
        <td class="td2"><input type="password" name="pass" /></td>
    </tr>
</table>
<div><button onClick="validate()" class="cupid-greenx">Login now</button></div>

The alert box is showing, but it shows "undefined".

Answer

Aidanc picture Aidanc · Apr 24, 2012

The reason you're seeing that error is because document.getElementsByName returns a NodeList of elements. And a NodeList of elements does not have a .value property.

Use this instead:

document.getElementsByName("acc")[0].value