sgrontflix sgrontflix - 26 days ago 5
HTML Question

getElementById() returns null on first element

The following code is my simple registration form. The problem is that

alert(elements[0].value)
displays
undefined
instead of the value of
name
(which is the first element of my form). However, if I try to execute
alert(elements[1].value)
, it displays the value of
name
without any problem. Any ideas?

<html>
<body>
<form name="register" id="register" method="POST" action="this-file.php">
<fieldset>
<legend><span style="color:red; font-size:20px">
Register</span></legend><br>

<label for="firstname">First name<span style="color:red;">*</span></label>
<input type="text" name="firstname" id="firstname" placeholder="Peter"
autofocus required><br><br>

<label for="lastname">Last name<span style="color:red;">*</span></label>
<input type="text" name="lastname" id="lastname" placeholder="Parker"
required><br><br>

<label for="password">Password<span style="color:red;">*</span></label>
<input type="password" name="password" id="password" required><br><br>

<label for="favfood">Favorite food<span style="color:red;">*</span></label>
<select name="favfood" id="favfood" required>
<option value="" selected>(none)</option>
<option value="chicken">Chicken</option>
<option value="pizza">Pizza</option>
<option value="pasta">Pasta</option>
<option value="hamburger">Hamburger</option>
<option value="steak">Steak</option>
</select>
<p>Gender<span style="color:red;">*</span></p>
<ul>
<li>
<input type="radio" name="gender" id="male" value="male" required>
<label for="male">Male</label>
</li>
<li>
<input type="radio" name="gender" id="female" value="female" required>
<label for="female">Female</label>
</li>
</ul>
</fieldset><br>
<input type="submit" value="Register" name="register">
<input type="reset" value="Clear form" name="clear"><br><br>
</form>
<script type="text/javascript">
var form = document.getElementById('register');
var elements = form.elements;

form.noValidate = true;
form.addEventListener('submit', function (event) {
alert(elements[0].value); //displays "undefined" -- why?
for (var i = 0; i < elements.length; i++) {
if (elements[i].hasAttribute("required")) {
if (!elements[i].checkValidity()) {
event.preventDefault();
alert('Please, fill in every required field.');
form.reset();
elements[0].focus();
break;
}
}
}
}, false);
</script>
</body>
</html>

Answer

The first element in the elements collection is the <fieldset>. It doesn't have a name or a value.

(Yes, I know it doesn't really make sense for elements to include fieldsets, but it does).

Test the value of theelement.tagName to see if you are dealing with an input/select/textarea before trying to run your validation routine on it.