JavaScript get element by name
JavascriptHtmlDomJavascript Problem Overview
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".
Javascript Solutions
Solution 1 - Javascript
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
Solution 2 - Javascript
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]
Solution 3 - Javascript
All Answers here seem to be outdated. Please use this now:
document.querySelector("[name='acc']");
document.querySelector("[name='pass']")
Solution 4 - Javascript
You want this:
function validate() {
var acc = document.getElementsByName('acc')[0].value;
var pass = document.getElementsByName('pass')[0].value;
alert (acc);
}
Solution 5 - Javascript
Method document.getElementsByName returns an array of elements. You should select first, for example.
document.getElementsByName('acc')[0].value
Solution 6 - Javascript
document.getElementsByName("myInput")[0].value;
Solution 7 - Javascript
Just for completeness so others reading this have a good idea of safety nets, especially with no guarantee to get the element you want, you could test for missing values, using null coalesce to set a default:
const accElements = document.getElementsByName('acc');
const accElement = accElements[0] ?? null; // Or some other value
if (!accElement) {
// handle the problem
}
And use Optional chaining when it's connected objects (and not arrays/nodes being returned):
const acc = document.getElementById('acc')?.value ?? null; // Or some other value
Also, while the name
attribute is sometimes all that is available, do try to use id
where possible as they have more chance of being unique. Assuming that your desired element is in results index 0 ([0]
) is usually safe, but better to check and be sure. For a few lines of code (with some logging perhaps) you save your end users the problems of things breaking.