JavaScript get element by name

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

Answers:

Answer

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
Answer

Note the plural in this method:

document.getElementsByName()

That returns an array of elements, so use [0] to get the first occurence, e.g.

document.getElementsByName()[0]
Answer

You want this:

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

    alert (acc);
}
Answer

Method document.getElementsByName returns an array of elements. You should select first, for example.

document.getElementsByName('acc')[0].value
Answer
document.getElementsByName("myInput")[0].value;

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.