I cannot figure out why appendChild is returning undefined.
I also tried t.previousSibling.appendChild(document.createElement('span')); which returns “previousSibling undefined”.
I need to add a span element with class of “error” to the span, withing the textnode of the label. So I loop through all the inputs and look for one that is empty, if it’s empty, it should add “*required” message next to the input label. I’ve got lots of ideas, but not sure where the problem lies. THANKS for your help!
var obj = {
inputs: document.getElementsByTagName("input"),
btn: document.getElementById('submit'),
init : function() {
obj.btn.onclick = obj.submitForm();
},
submitForm : function() {
for (var i=0; i<obj.inputs.length; i++) {
if (obj.inputs[i].value==="") {
switch(obj.inputs[i].name) {
case "fname" : match=true; obj.error("fname");
case "lname" : match=true; obj.error("lname");
}
}
}
},
error : function(t) {
var err = "*required";
var j = t.previousSibling.appendChild(document.createElement('span'));
j.className = "error";
j.appendChild(document.createTextNode(err));
}
}
Here is HTML:
<head>
<title>Homework 9 JavaScript form</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
<form method="post" action="">
<div>
<ul>
<li><label>First Name</label><input type="text" id="fname" name="fname" size="30" /></li>
<li><label>Last Name</label><input type="text" name="lname" size="30" /></li>
<li><label>Phone</label><input type="text" name="phone" size="30" /></li>
<li><label>Email</label><input type="text" name="email" size="30" /></li>
<li><input type="submit" name="submit" id="submit" value="Submit" />
</ul>
</div>
</form>
<script type="text/javascript" src="hw9.js"></script>
<script type="text/javascript">obj.init();</script>
</body>
</html>
The
errormethod appears to expect a DOM object as an argument, but you’re passing it strings. At least, the strings probably don’t have apreviousSiblingproperty that would have anappendChildmethod.You can either pass along the objects you’re already checking against:
Or, you can change
errorto expect a string. Either anid— if you give<input name="lname">anid="lname":Or by a
name:Also, be sure to
breakeachcasethat you don’t want to fall-through into subsequent cases: